2017-02-23 43 views
0

我有簡單的wpf應用程序,我試圖將文件從一個文件夾移動到其他文件夾。我的文件是RTC.hex在桌面上。我正試圖將它移到D盤中的一個文件夾中。代碼:無法將文件從一個文件夾移動到其他WPF C#

private void Move_ButtonClick(object sender, RoutedEventArgs e) 
    { 

     Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 
     Nullable<bool> result = dlg.ShowDialog(); 
     if (result == true) 

     { 

      string filename = dlg.SafeFileName; 

      System.IO.File.Move(filename, @"D:\New Folder\" + filename); 

     } 


    } 

但它顯示了以下錯誤:

enter image description here

我在這裏做什麼錯?

回答

0

使用FileDialog的年代FileName屬性,而不是SafeFileName,因爲它包含了一個完整的路徑:

SafeFileName頁面上MSDN:

This value is the FileName with all path information removed.

你還可以創建目標文件夾,然後才能寫入。

var targetDir = @"D:\New Folder"; 

System.IO.Directory.CreateDirectory(targetDir); 
System.IO.File.Move(filename, 
    System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(filename))); 
+0

是的,也試過了。但現在它顯示'找不到路徑D:\\新建文件夾\\的一部分,但路徑是正確的。 –

+0

好吧,但我沒有得到它。爲什麼我們需要在移動文件之前創建文件夾。有必要嗎。? –

+0

是的,顯然。 – Clemens

0

你的文件名變量中的哪個值在運行時間? 他們應該是你的桌面文件夾(C:/用戶/桌面)+'RTC.hex'的路徑。 (適用於Windows 7和8)

對於較早的Windows操作系統,桌面路徑可能不同。

相關問題