【发布时间】:2014-01-28 00:49:16
【问题描述】:
我厌倦了将包含特定字符串的文件从一个文件夹复制到另一个文件夹,但它一直给我错误消息 System.IO.IOException: The process cannot access the file 'Z:\Upload\Text-File-1.txt ' 因为它正被另一个进程使用。尝试了一些东西,但没有任何效果。不知道怎么解决。
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CheckandMoveFiles();
}
private static void CheckandMoveFiles()
{
//put filenames in array
string[] sourcePath = Directory.GetFiles(@"Z:\Upload\");
string targetPath = @"Z:\Upload\TextFiles\";
try
{
//Get each filepath and check for string
foreach (string name in sourcePath)
{
string d = "Text";
if (name.Contains(d))
{
string fileName = name;
string sourceFile = System.IO.Path.Combine(sourcePath.ToString(), fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
using (StreamReader reader = new StreamReader(sourceFile))
{
File.Copy(sourceFile, destFile, true);
}
}
}
}
catch (IOException ex)
{
Console.WriteLine(ex); // Write error
}
Console.WriteLine("****************************DONE***************************************");
Console.ReadLine();
}
}
}
【问题讨论】:
-
不确定这是否会导致错误 - 但似乎不太可能:您到底为什么要先打开文件进行读取,然后尝试通过文件系统复制它?
标签: c#