在c#中移动包含值的文本文件
我试图移动一个文件,如果它包含一个特定的字符串,代码如下在c#中移动包含值的文本文件,c#,file,C#,File,我试图移动一个文件,如果它包含一个特定的字符串,代码如下 foreach (FileInfo file in files) { //reads the file contents string MessageContents = File.ReadAllText(file.FullName); //checks if the textwords are present in the file
foreach (FileInfo file in files)
{
//reads the file contents
string MessageContents = File.ReadAllText(file.FullName);
//checks if the textwords are present in the file
foreach (string Keyword in textwords)
{
//if they are file is moved to quarantine messages
if (MessageContents.Contains(Keyword))
{
try
{
File.Move(file.FullName, File_quarantine);
}
catch (IOException cannot_Move_File)
{
MessageBox.Show("The process has failed: {0}", cannot_Move_File.ToString());
}
break;
}
//else it is moved To valid messages
else
{
try
{
File.Move(file.FullName, File_Valid);
}
catch (IOException cannot_Move_File)
{
MessageBox.Show("The process has failed: {0}", cannot_Move_File.ToString());
}
break;
}
}
}
}
但是,该过程总是失败,错误在mscorlib.dll中发生了“System.IO.IOException”类型的第一次意外异常
我不确定为什么会发生这种情况,如果您能提供任何帮助,我们将不胜感激。您仍然锁定了该文件,因为您打开了一个指向该文件的流。将文件移出读取文件的逻辑
这将产生预期的结果
foreach (FileInfo file in files)
{
String messageContents = File.ReadAllText(file.FullName);
bool toQuarantine = textwords.Any(keyWord => messageContents.Contains(keyWord));
try
{
File.Move(file.FullName, toQuarantine ? File_quarantine : File_Valid);
}
catch (IOException cannot_Move_File)
{
MessageBox.Show("The process has failed: {0}", cannot_Move_File.ToString());
}
}
基本上你已经锁定了文件。你不能在阅读时移动它
如果文件相对较小,可以使用以下技术:
String content = File.ReadAllText( filename );
// at this point, the file is not locked, unlike the
// way it is in your question. you are free to move it
foreach (String keyword in keywords) {
if (content.Contains(keyword)) {
// Move file
break;
}
}
您仍然对该文件有一个锁,因为您打开了一个指向该文件的流。将文件移出读取文件的逻辑。查看我的答案。我使用的try-and-catch方法是否适用于您指定的//Move File
我编辑了问题以反映您的建议,但是我仍然收到相同的错误消息异常消息是什么?(您之前没有指定)我收到的错误是System.IO.IOException:当文件已经存在时,无法创建文件。
但是,该文件不存在于我试图将其移动到的目标文件夹中,这可能是因为file\u quantial
和file\u Valid
始终相同,因此,它将在第二个有或没有任何关键字的文件上失败。如果您不介意覆盖文件,您可以先测试文件是否存在,然后将其删除。因此,例如,在try
方法中放入for
语句,以检查文件是否存在?@bdg No您必须这样做;为每个文件指定唯一的字符串,或在移动前删除该文件,或使用“复制并覆盖”,然后使用“删除”而不是“移动”。