我正在寫一個非常小的應用程序從一個地方複製目錄到另一個與一些額外的自動化。整個應用程序完美地工作,除了實際的複製方法。最糟糕的是我沒有得到任何的錯誤,而且正如大多數人所知道的那樣,這比得到錯誤要糟糕得多。C#目錄複製返回沒有錯誤,但不復制目錄
這裏是有問題的方法:
- SPATH:
"C:\\Users\\Jacob Jewett\\Downloads\\func1"
- dPath:
"C:\\Users\\Jacob Jewett\\AppData\\Roaming\\.minecraft\\saves\\data\\functions\\"
- 文件:
public static bool CopyDir(string sPath, string dPath) { string[] files = Directory.GetFiles(sPath); try { foreach (string file in files) { string name = Path.GetFileName(file); foreach (string dirPath in Directory.GetDirectories(sPath, "*", SearchOption.AllDirectories)) Directory.CreateDirectory(dirPath.Replace(sPath, dPath)); foreach (string newPath in Directory.GetFiles(sPath, "*.*", SearchOption.AllDirectories)) File.Copy(newPath, newPath.Replace(sPath, dPath), true); } } catch // this is no use because the Exception is empty. { return false; } return false; //the app keeps executing to here and I don't know why }
從調試器變量轉儲[0]
"C:\\Users\\Jacob Jewett\\Downloads\\func1\\main.mcfunction"
Downloads\func1
(SPATH)的文件夾樹:
func1
main.mcfunction
編輯(下午2:33):行,所以這是我的重構的代碼,則返回錯誤File in use
但不會複製任何東西。
public static bool CopyDir(string sPath, string dPath)
{
try
{
foreach (string dirPath in Directory.GetDirectories(sPath, "*",
SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(sPath, dPath));
foreach (string newPath in Directory.GetFiles(dPath, "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sPath, dPath), true);
return true;
}
catch (UnauthorizedAccessException e)
{
MessageBox.Show("Attempt to copy failed. Raw: "+e,"IO Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
編輯(17年8月29日下午12:09):我已經做了一些調整方法和我在一個點上我,我現在得到一個Access to path [path] is Denied.
,這是比什麼都沒有,只有更好我還沒有遇到過工作解決方案。我在這裏做了一些瀏覽錯誤,大多數人在調用File.Copy()
方法之前先說File.SetAttributes()
。這沒有效果。另外,我嘗試在完成任何複製之前將sPath1
的Read-Only
目錄的屬性設置爲none,並且這也沒有效果。
當前代碼:
public static bool CopyDir(string sPath, string dPath)
{
try
{
DirectoryInfo spdi = new DirectoryInfo(sPath);
spdi.Attributes &= ~FileAttributes.ReadOnly;
foreach (string dirPath in Directory.GetDirectories(sPath, "*",
SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath);
foreach (string newPath in Directory.GetFiles(dPath, "*.*",
SearchOption.AllDirectories))
{
File.SetAttributes(dPath, FileAttributes.Normal);
File.Copy(sPath, newPath);
}
Directory.CreateDirectory(dPath);
return true;
}
catch (UnauthorizedAccessException e)
{
MessageBox.Show("Attempt to copy failed. (UAC) Raw: "+e,"IO Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
它很可能在'catch'塊內觸發'return false'。你遇到了一個例外,但它只是被吞下,你永遠不會看到錯誤。 –
我曾嘗試添加更好的catch塊,並且異常不會返回任何內容。它甚至不能從我所能看到的捕獲塊中去除。 –
你是否嘗試過使用調試器? – itsme86