我有以下代码,它使用计时器为我移动文件(每10分钟移动200个文件或我在设置表格中保存的内容)。
问题是文件在打开和写入时会被移动,我知道我必须在我的程序中“打开”它并检查异常,但我无法弄清楚我的代码应该放在哪里?
try
{
string origDir = @"" + Properties.Settings.Default.MoveFrom;
string destDir = @"" + Properties.Settings.Default.MoveTo;
string oldDir = @"" + Properties.Settings.Default.MoveToOld;
int filesPerMove = Properties.Settings.Default.FilesPerMove;
int i = 0;
DateTime dateMove= DateTime.Now;
DirectoryInfo dirInfo = new DirectoryInfo(origDir);
FileInfo[] files = dirInfo.GetFiles("*.txt");
foreach (string file in Directory.GetFiles(origDir))
if (new FileInfo(file).Length > 0)
{
if (i < filesPerMove)
{
ListViewItem lviSuccess = new ListViewItem(origFile.Name);
lviSuccess.SubItems.Add(origFile.LastWriteTime.ToString());
lviSuccess.SubItems.Add(dateMove.ToString());
lviSuccess.SubItems.Add(origFile.Length.ToString());
lviSuccess.SubItems.Add(origDir.ToString());
lviSuccess.SubItems.Add(destDir.ToString());
lvFileMoves.Items.Add(lviSuccess);
lviSuccess.UseItemStyleForSubItems = true;
lviSuccess.ForeColor = Color.Green;
FileInfo destFile = new FileInfo(file.Replace(origDir, destDir));
FileInfo destFile1 = new FileInfo(file.Replace(origDir, oldDir));
System.IO.File.Copy(origFile.FullName, destFile1.FullName, true);
System.IO.File.Copy(origFile.FullName, destFile.FullName, true);
File.Delete(origFile.FullName);
i++;
}
}
}
catch (System.IO.IOException ex)
{
ListViewItem lvi = new ListViewItem(ex.Message);
lvFileMoves.Items.Add(lvi);
lvi.UseItemStyleForSubItems = true;
lvi.ForeColor = Color.Red;
}
答案 0 :(得分:1)
答案 1 :(得分:0)
您应该将异常处理放在文件处理附近:
try
{
FileInfo destFile = new FileInfo(file.Replace(origDir, destDir));
FileInfo destFile1 = new FileInfo(file.Replace(origDir, oldDir));
System.IO.File.Copy(origFile.FullName, destFile1.FullName, true);
System.IO.File.Copy(origFile.FullName, destFile.FullName, true);
File.Delete(origFile.FullName);
i++;
}
catch(System.IO.IOException ex)
{
ListViewItem lvi = new ListViewItem(ex.Message);
lvFileMoves.Items.Add(lvi);
lvi.UseItemStyleForSubItems = true;
lvi.ForeColor = Color.Red;
}
这样,当一个文件失败时,您可以继续使用以下文件。
答案 2 :(得分:0)
现在我有下面的内容,但即使对于我没有在记事本中打开过的文件,它也会为每个文件设置一个异常。
FileStream outStream = null;
try
{
outStream = File.OpenWrite(origFile.ToString());
FileInfo destFile = new FileInfo(file.Replace(origDir, destDir));
FileInfo destFile1 = new FileInfo(file.Replace(origDir, oldDir));
System.IO.File.Copy(origFile.FullName, destFile1.FullName, true);
System.IO.File.Copy(origFile.FullName, destFile.FullName, true);
File.Delete(origFile.FullName);
lblSenast.Text = string.Format("Senaste flytt gjordes {0}", dateMove.ToString());
}
catch (IOException exx)
{
ListViewItem lvi = new ListViewItem(exx.Message);
lvFileMoves.Items.Add(lvi);
lvi.UseItemStyleForSubItems = true;
lvi.ForeColor = Color.Gray;
}
finally
{
outStream.Close();
outStream.Dispose();
}
该进程无法访问文件“Bla bla bla”因为它正被另一个进程使用