3 回答

TA貢獻1839條經驗 獲得超15個贊
如果文件不存在,File.Delete實際上不會引發任何異常。因此,我將完全刪除存在的檢查。
try {
int delay = 400;
File.Delete(@"C:\Users\Admin\source\Bargstedt.csv");
Thread.Sleep(delay); // to prevent delete and copy happening at the
// same time.
System.IO.File.Copy(s, destFile, true);
}catch (IOException ex) {}
您還可以查看此帖子:
C# 中的 FileStream 和 FileSystemWatcher,奇怪的問題“進程無法訪問文件” 和用戶 EventHorizon 的答案檢查文件是否已關閉。
還建議檢查目錄是否有權限 (FileIOPermissionAccess.Write)

TA貢獻1772條經驗 獲得超6個贊
我想你的意思是即使有文件也要寫文件。
您正在使用:
bool exists = info.Exists;
if (exists == true)
{
File.Delete(@"C:\Users\Admin\source\Bargstedt.csv");
}
else
{
System.IO.File.Copy(s, destFile, true);
}
刪除其他:
bool exists = info.Exists;
if (exists == true)
{
File.Delete(@"C:\Users\Admin\source\Bargstedt.csv");
}
System.IO.File.Copy(s, destFile, true);

TA貢獻1936條經驗 獲得超7個贊
當文件存在于目標路徑中并具有該現有文件的備份計劃時,使用它來復制文件。
// To copy a file to another location and
// overwrite the destination file if it already exists.
if (!File.Exists(destFile))
{
System.IO.File.Copy(sourceFile, destFile, true);
}
else
{
System.IO.File.Move(destFile, existingFilePath); //if file is existing and then move it to specific folder
try
{
System.IO.File.Copy(sourceFile, destFile, true);
}
catch (Exception)
{
System.IO.File.Move(existingFilePath, destFile); //If anythig went wrong, old file is relocated correctly
}
System.IO.File.Delete(existingFilePath); // Delete old file, all is ok now.
}
- 3 回答
- 0 關注
- 233 瀏覽
添加回答
舉報