views:

34

answers:

1

Hey.

Doing a file upload to an aspx page from C#. Getting a:

PathTooLongException
The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Here's the code:

            try
            {
                using (var client = new WebClient())
                {
                    String url =
                        String.Format(
                            "http//localhost:49536/ManualUploadTest.aspx?key={0}&name={1}&address={2}&phone={3}&email={4}&node={5}",
                            "changeme",
                            "john",
                            "10 Downing Street",
                            "555 555 6165",
                            "[email protected]",
                            "TestNode");

                    var len = url.Length;  // this length is 146 
                    var encodeLen = HttpUtility.UrlEncode(url).Length; // this length is 180

                    //client.BaseAddress = "http//localhost:49536";

                    byte[] result = client.UploadFile(HttpUtility.UrlEncode(url), path);

                    // throws exception during UploadFile
                    // ... more code here

The url string looks like this:

http//localhost:49536/ManualUploadTest.aspx?key=changeme&name=john&address=10 Downing Street&phone=555 555 6165&[email protected]&node=TestNode

The path is:

Y:\\10mb.zip

Thanks for any help!

+2  A: 

Try fixing the URL: http://... instead of http//...; also, I'd use the Uri class and not UrlEncode().

Uri url = new Uri(String.Format("http://localhost:49536/ManualUploadTest.aspx?key={0}&name={1}&address={2}&phone={3}&email={4}&node={5}",
                                HttpUtility.UrlEncode("changeme"),
                                HttpUtility.UrlEncode("john"),
                                HttpUtility.UrlEncode("10 Downing Street"),
                                HttpUtility.UrlEncode("555 555 6165"),
                                HttpUtility.UrlEncode("[email protected]"),
                                HttpUtility.UrlEncode("TestNode")));
byte[] result = client.UploadFile(url, path);

Edit: I tracked down the reason for exception... if you supply a string, it tries to create a Uri internally (which fails because of the malformed protocol http//), then it tries to get the full path for the Uri using Path.GetFullPath(url), and this then fails with the PathTooLongException.

Lucero
perfect, thanks! using the uri stuff now but it also works with a string. was just because we had http// silly mistake but awful exception for it.
nextgenneo
The problem with the string variant it that it may not encode what you want. If any of the values you're putting in the url with your string.Format() contain either `?` or `=` they will break your url and not get encoded correctly. You need to UrlEncode the single values to avoid this.
Lucero