2010-10-17 71 views
2

做一個文件上傳到從C#的aspx頁面。獲得一個:C#的WebClient UploadFile給我PathTooLongException(它不會太長!)

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. 

下面的代碼:

  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 

URL字符串看起來是這樣的:

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

的路徑是:

Y:\\10mb.zip 

感謝您的幫助!

+0

你打算怎麼上傳?你從服務器端上傳嗎? 我想你需要一個FileUpload控件(INPUT TYPE =文件) – abhishek 2010-10-17 20:17:58

回答

4

嘗試固定的網址:http://...代替http//...;此外,我會使用Uri類而不是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); 

編輯:我找到了異常的原因......如果你提供一個字符串,它會嘗試在內部創建一個URI(這將失敗,因爲畸形協議http//的),那麼它會嘗試使用Path.GetFullPath(url)獲得Uri的完整路徑,然後PathTooLongException失敗。

+0

完美,謝謝!現在使用uri的東西,但它也適用於一個字符串。只是因爲我們有http //很愚蠢的錯誤,但卻是非常糟糕的例外。 – 2010-10-17 21:12:58

+0

字符串變體的問題,它可能不會編碼你想要的。如果你在string.Format()中放入url的任何值包含'?'或'=',那麼它們會破壞你的url並且不能正確編碼。你需要UrlEncode單個值來避免這種情況。 – Lucero 2010-10-17 21:18:36