首页 > 解决方案 > C# System.IO IOException“无法访问文件,因为它被另一个进程访问”

问题描述

我是使用System.IO的新手,我无法弄清楚为什么我的代码会导致此异常。我想检查一个目录和一个文件是否存在,如果不存在,我想创建它们。之后,我想在我刚刚创建的文件上写一些东西。在这里它抛出异常。我非常确定当我尝试使用StreamWriter时创建会导致异常,因为如果文件已经存在,我不能得到一个执行。此外,当我在一次尝试失败后再次单击调用此功能的按钮时,没有例外,一切正常(看起来我的程序在刷新 UI 后意识到没有打开的进程)。我不明白,似乎还有什么其他进程正在访问该文件,我认为在使用FileInfo.Create()功能后我不需要关闭任何流。

这是我的代码:

public static void Save_map(int[,] p_temp_map_property, string p_filename)
    {
        temp_map_property = p_temp_map_property;
        try
        {
            DirectoryInfo MapsDirectory = new DirectoryInfo("Maps");
            DirectoryInfo Map = new DirectoryInfo(@"Maps\" + p_filename);
            FileInfo file = new FileInfo(@"Maps\" + p_filename + @"\" + p_filename + ".txt");
            if (!MapsDirectory.Exists)
            {
                MapsDirectory.Create();
            }

            if (!Map.Exists)
            {
                Map.Create();
            }

            if (!file.Exists)
            {
                file.Create();
            }

            StreamWriter sw = new StreamWriter(@"Maps\" + p_filename + @"\" + p_filename + ".txt", false);
            
            for(int n = 0; n < 140; n++)
            {
                for(int m = 0; m < 90; m++)
                {
                    sw.WriteLine(p_temp_map_property[n, m]);
                }
            }
            sw.Close();
            sw.Dispose();
            MessageBox.Show("Map saved successfully!");
        }
        catch(Exception e)
        {
            MessageBox.Show(e.ToString());
        }
    }

一个例外:

Exception thrown: "System.IO.IOException" in mscorlib.dll
System.IO.IOException: The procces cannot acsses "C:\Users\User\source\repos\Map Editor TD\Map Editor TD\bin\Debug\Maps\test\test.txt" because it is accsessed in another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
   at System.IO.StreamWriter..ctor(String path, Boolean append)
   at Map_Editor_TD.Save_to_File.Save_map(Int32[,] p_temp_map_property, String p_filename) in C:\Users\User\source\repos\Map Editor TD\Map Editor TD\Save_to_File.cs:Zeile 39.

我希望比我更有经验的人可以帮助我解决这个问题。提前致谢。

标签: c#.net

解决方案


file.Create();使文件保持打开状态,并返回一个句柄。要么先关闭它,要么用它来写东西。

下面的代码使用它:

public static void Save_map(int[,] p_temp_map_property, string p_filename)
{
    temp_map_property = p_temp_map_property;
    try
    {
        DirectoryInfo MapsDirectory = new DirectoryInfo("Maps");
        DirectoryInfo Map = new DirectoryInfo(@"Maps\" + p_filename);
        FileInfo file = new FileInfo(@"Maps\" + p_filename + @"\" + p_filename + ".txt");
        if (!MapsDirectory.Exists)
        {
            MapsDirectory.Create();
        }

        if (!Map.Exists)
        {
            Map.Create();
        }

        using (FileStream fileStream = file.Exists ? file.OpenWrite() : file.Create())
        using (StreamWriter sw = new StreamWriter(fileStream, false))
        {
            for (int n = 0; n < 140; n++)
            {
                for (int m = 0; m < 90; m++)
                {
                    sw.WriteLine(p_temp_map_property[n, m]);
                }
            }
        }
        
        MessageBox.Show("Map saved successfully!");
    }
    catch(Exception e)
    {
        MessageBox.Show(e.ToString());
    }
}

推荐阅读