2014-09-30 83 views
0

我有一個。 aspx頁面,它在Button click上動態創建HTML文件。已成功創建.html頁面,但無法使用File.Copy方法將copy創建的文件轉換爲destination使用C複製文件時出錯#

代碼背後:

protected void btnPublish_Click(object sender, EventArgs e) 
    { 
     //copy the created file content to destination 
     string sourcePath=string.Empty; 
     string destiPath = @"d://test//"; 
     if(!string.IsNullOrEmpty(hdnPublishPath.Value)) 
     { 
      sourcePath= hdnPublishPath.Value; 
      if (!Directory.Exists(destiPath)) // check if folde exist 
      { 
       Directory.CreateDirectory(destiPath); // create folder 
       //Directory.Delete(destiPath, true); // delete folder 
      } 

      File.Copy(sourcePath, destiPath,true); 
     } 
    } 

它提供了異常:目錄未發現異常。 (:/ d),但文件複製失敗

enter image description here

目錄被提到驅動器上創建。

注:目前的路徑是「本地」,但後來這個文件將被複制到任何遠程服務器位置

+0

把@ @ d:/ test /「'或'」d:\\ test \\「' – 2014-09-30 05:57:56

回答

1

你會想有路徑和文件名作爲您的目的地,而不是直接ory:

File.Copy(sourcePath, Path.Combine(destiPath, filename)); 

如果你只提供目標目錄,你將會得到你現在得到的異常。

+0

感謝@Fredrik Mork你值得+1 :) – 2014-09-30 06:21:10

0

你需要下面爲你不需要添加「給路徑@」或者你可以簡單地寫@"d:/test/": -

protected void btnPublish_Click(object sender, EventArgs e) 
    { 
     //copy the created file content to destination 
     string sourcePath=string.Empty; 
     string destiPath = "d://test//"; 
     if(!string.IsNullOrEmpty(hdnPublishPath.Value)) 
     { 
      sourcePath= hdnPublishPath.Value; 
      if (!Directory.Exists(destiPath)) // check if folde exist 
      { 
       Directory.CreateDirectory(destiPath); // create folder 
       //Directory.Delete(destiPath, true); // delete folder 
      } 

      File.Copy(sourcePath, destiPath,true); 
     } 
    } 

欲瞭解更多信息,一看: -

http://msdn.microsoft.com/en-us/library/362314fe.aspx

+0

不好意思說@Neel但是仍然給出錯誤:找不到路徑的一部分'd:\測試\'。 – 2014-09-30 06:04:10

+1

問題不在於目錄不存在,而是File.Copy調用沒有目標*文件名*,而只有目標*目錄*。 – 2014-09-30 06:06:53

2

有一個語法錯誤destiPath

... 
    // That's incorrect: 
    // string destiPath = @"d://test//"; 

    // Should be like this 
    string destiPath = @"d:\test\"; 
    // ... or like that 
    string destiPath = "d:\\test\\"; 
    ... 

File.Copy另一個問題:您應該提供文件名,而不是目錄名稱:

... 
    // Incorrect 
    // File.Copy(sourcePath, destiPath,true); 

    // Should be something like 
    File.Copy(Path.Combine(sourcePath, "myFile.txt"), Path.Combine(destiPath, "myFile.txt"), true); 
+0

這也不會工作:( – 2014-09-30 06:05:14

+0

實際上,它與正斜槓一樣好,反斜槓也是這樣,系統計算出來。 – 2014-09-30 06:06:02

+0

@FredrikMörk:是的,'Path.AltDirectorySeparatorChar'和'Path.DirectorySeparatorChar'都很好;我只是想用'@'和雙斜槓顯示兩種格式'\\' – 2014-09-30 06:10:38