当我使用 File.Move 时,它被调用了两次并导致错误

When I use File.Move, its called twice and causes errors

提问人:Ctrying 提问时间:9/2/2023 最后编辑:marc_sCtrying 更新时间:10/25/2023 访问量:43

问:

我遇到的问题是,当我尝试将文件移动到其他目录时,我收到一个错误,指出该文件在您要从中移动的当前目录中不存在。但是,当我检查时,文件实际上已被移动。

我已经看到它运行了两次。在我的代码中,我使用:

StreamReader reader = null;
reader = new StreamReader(File.OpenRead(path+"/"+fileName));

这用于获取所需的详细信息。我也试图在使用后关闭/处理它。但是,当我尝试在使用 后移动文件时,它会立即运行两次。因此,即使使用也行不通。File.OpenReadthread.sleep

我还尝试使用不起作用的锁。

if (File.Exists(path + "/" + fileName))
{
    lock (fileMoveLock)
    {
        string timeStamp = GetTimestamp(DateTime.Now);
        Console.WriteLine(timeStamp);

        string fileNameSlice = fileName.Substring(0, (fileName.Length - 4));
        string finalPath = fileNameSlice + "_" + timeStamp + ".txt";

        try
        {
            File.Move(path + "/" + fileName, Path.Combine(path + "/archive", finalPath));
            Console.WriteLine($"File moved: {path + "/" + fileName} to {finalPath}");
        }
        catch (Exception ex)
        {
            // Handle any exceptions that may occur during the move operation
            Console.WriteLine($"Error moving file: {ex.Message}");
        }
    }
}
else
{
    // Handle the case where the file does not exist
    return;
}

这是我用来移动文件的代码。当我删除移动前使用的代码行时,这有效。File.OpenRead

从本质上讲,该程序正在尝试读取文件并获取所需的详细信息,然后移动它。它已成功移动,但同时运行两次。我已经尝试了几个小时,发现它正在干预某些事情。File.Open

我需要打开文件才能工作,因为这会读取我需要的数据。

编辑:这是我能找到的唯一解决方案,但我不知道这是否真的是不好的做法

try
{
    StreamReader reader = null;
    reader = new StreamReader(File.OpenRead(path + "/" + fileName));
}
catch (Exception ex) 
{
    return;
}
C# .NET IO 系统.io.file

评论

0赞 Theodor Zoulias 9/2/2023
您是否也使用具有相同 locker 对象的语句,围绕执行 ?lockFile.OpenRead
0赞 Theodor Zoulias 9/2/2023
你有没有试过把里面的?if (File.Exists(lock
2赞 Fildor 9/2/2023
考虑发布一个实际的最小可重现示例

答:

0赞 Greg The Packrat 9/2/2023 #1

这听起来像是您正在尝试打开一个文件,读取其内容,然后将文件移动到另一个文件夹,大概是为了将其标记为已处理。您的代码似乎与您对正在发生的事情的描述不符;我怀疑你的第一个片段在一个函数中,由于某种原因被调用了两次。

StreamReader 确实是读取文件的好方法,但您只需要提供文件名的路径;不需要 File.OpenRead 的输出。您应该确保在移动文件之前关闭文件。也许是这样的:

    // Put your file paths in these strings.
    string oldpath = "current file path";
    string newpath = "new file path";
    string contents = "";
    using (StreamReader sr = new StreamReader(oldpath))
    {
        // The using keyword makes sure that disposable objects like StreamReader
        // are automatically cleaned up. In this case, it closes the file, too.
        contents = sr.ReadToEnd();
    }
    File.Move(oldpath, newpath);

文件的内容仍在局部变量中,因此现在您可以对该数据执行所需的操作。