如果文本文件包含值,则在c#中移动该文本文件

时间:2016-04-07 10:58:45

标签: 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 (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;
                    }
                }
            }
        }

但是,该过程始终失败并显示错误A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll

我不确定为什么会发生这种情况,我们将非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您仍然锁定文件,因为您打开了一个流。移动将文件移出文件读取的逻辑。

这应该产生预期的结果;

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());
    }
}

答案 1 :(得分:0)

基本上你锁定了文件。你在阅读时无法移动它。

如果文件相对较小,您可以使用以下技术:

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;
    }
}