[英]File.Move only Copy the file
我有一個應用程序,該應用程序生成文件后,嘗試使用File.Move函數將其從網絡位置移動到本地文件夾。
File.Move(_backupSource + @"\" + filename, _backupDestination + @"\" + filename);
_backupSource是網絡位置,_backupDestintation是本地文件夾。
該文件被復制到目標位置,幾天之內並沒有刪除源文件 ,就像我使用File.Copy一樣,但是這種復制現在可以正常工作兩個月了。
我還從兩台服務器查看了事件查看器,沒有生成異常。
¿會發生什么?
編輯:一件事可能很重要。 每晚,任務調度程序都會觸發此應用。 如果我手動運行應用程序,文件將被移動(未復制)
編輯2:現在我試圖復制文件,然后使用以下方法刪除文件
private static void MoveFiles(string filename)
{
FileInfo file = new FileInfo(_backupSource + @"\" + filename);
FileStream stream = null;
int iteration = 0;
file.CopyTo(_backupDestination + @"\" + filename);
bool isUnlocked = false;
while (!isUnlocked)
{
iteration++;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
isUnlocked = true;
}
catch (IOException ex)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
Thread.Sleep(60 * 1000);
if (iteration > 60)
throw ex;
else
EventLog.WriteEntry("DailyRestore", string.Format("Move File. Iteration number {0}", filename), EventLogEntryType.Information);
}
finally
{
if (stream != null)
stream.Close();
}
}
file.Delete();
}
在日志中可以看到該應用每分鍾嘗試運行一個小時,並且該文件始終在“被另一個進程使用”。 就像我提到的那樣,這是由調度程序任務執行exe時,如果我運行手動執行exe的任務(右鍵單擊並執行),則所有操作均成功結束。
嘗試通過創建命令文件以管理員身份運行應用程序,以以管理員身份運行該應用程序,而不是調用該應用程序
runas.exe /savecred /user:YourUser "YourAppFullPath"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.