2011-08-23 67 views
1

我嘗試編寫一個控制檯應用程序C#將我的etxt文件移動到另一個文件夾。 功能只是複製從文件夾中的某個.txt文件到文件夾AA如何將txt文件移動到其他文件夾?

string source = "C:\\A\\ResultClassA.txt"; 
File.Move(Source, "C:\\AA"); 

但它總是給此錯誤消息:

對路徑的訪問被拒絕。

疑難解答提示: 確保您有足夠的權限訪問此資源。 如果您試圖訪問文件,請確保它不是隻讀。 獲取有關此例外的一般幫助。

在「File.move」代碼執行之前,我是否真的需要將我的文件夾A和文件夾B設置爲「NOT ReadOnly」屬性?並在成功移動後設置爲只讀回?

謝謝。 由英雄。

+0

沒有文件夾'C見here:\ AA'存在嗎? File.Move只是移動文件,它不會創建目錄。如果'source'文件正在使用或不可用,它也會失敗。 – Jodrell

+1

如果您想要了解有關異常的更多詳細信息,請在代碼中注意第二行中的Source應該是小寫。 –

回答

1

英雄,您正在從一個文件名移動到一個文件夾名稱,嘗試在C:\AA文件夾中指定一個帶擴展名的文件名。

AA上是否已經存在AA?

+0

它已經存在於我的C驅動器 – Hero

4

你需要指定的完整路徑,並確保路徑C:\AA存在

string source = "C:\\A\\ResultClassA.txt"; 
File.Move(Source, "C:\\AA\\ResultClassA.txt"); 

好的樣品

using System; 
using System.IO; 
class Test 
{ 
    public static void Main() 
    { 
     string path = @"c:\temp\MyTest.txt"; 
     string path2 = @"c:\temp2\MyTest.txt"; 
     try 
     { 
      if (!File.Exists(path)) 
      { 
       // This statement ensures that the file is created, 
       // but the handle is not kept. 
       using (FileStream fs = File.Create(path)) {} 
      } 

      // Ensure that the target does not exist. 
      if (File.Exists(path2)) 
      File.Delete(path2); 

      // Move the file. 
      File.Move(path, path2); 
      Console.WriteLine("{0} was moved to {1}.", path, path2); 

      // See if the original exists now. 
      if (File.Exists(path)) 
      { 
       Console.WriteLine("The original file still exists, which is unexpected."); 
      } 
      else 
      { 
       Console.WriteLine("The original file no longer exists, which is expected."); 
      }   

     } 
     catch (Exception e) 
     { 
      Console.WriteLine("The process failed: {0}", e.ToString()); 
     } 
    } 
} 
+0

雅沃..我也應該把文件名以及..非常感謝 – Hero

+0

大聲笑歡迎。如果它適合你,請不要忘記選擇其中一個答案 –

相關問題