C# 文件处理 - 创建文件并打开

2023-12-01

这就是我在文件上创建和写入的内容:

    Create_Directory = @"" + path;
    Create_Name = file_name;

    private void Create_File(string Create_Directory, string Create_Name )
    {
        string pathString = Create_Directory;
        if (!System.IO.Directory.Exists(pathString)) { System.IO.Directory.CreateDirectory(pathString); }

        string fileName = Create_Name + ".txt";
        pathString = System.IO.Path.Combine(pathString, fileName);
        if (!System.IO.File.Exists(pathString)) { System.IO.File.Create(pathString); }

        ///ERROR BE HERE:
        System.IO.StreamWriter file = new System.IO.StreamWriter(pathString);
        file.WriteLine(Some_Method(MP.Mwidth, MP.Mheight, MP.Mtype, "" )); 
        file.Close();
    }

我一整天都在努力解决的问题是在创建文件后写入文件。因此,我的程序很好地创建了一个文件,然后在写入之前给出了一个错误:

“mscorlib.dll 中发生了类型为‘System.IO.IOException’的未处理异常”

“附加信息:该进程无法访问文件“D:\Projects\Project 15\Project 15\world\world paths\A.txt”,因为该文件正在被另一个进程使用。”

有趣的是,当我再次运行该程序并尝试创建一个已经存在的文件时,如您所见,它会跳过文件创建,进入写入状态并且工作正常,而且我真的希望我的程序能够创建该文件并在不进行写入的情况下进行写入必须重新运行它...我在这里没有看到什么? :S


问题是文件.创建返回一个打开的Stream,而你永远不会关闭它。在您创建文件时,该文件(由您)“正在使用”StreamWriter.

话虽这么说,您不需要“创建”该文件。StreamWriter会自动为你做。只需删除这一行:

   if (!System.IO.File.Exists(pathString)) { System.IO.File.Create(pathString); }

一切都应该按照书面规定进行。

但请注意,我会稍微重写一下,以使其更安全:

private void Create_File(string directory, string filenameWithoutExtension )
{
    // You can just call it - it won't matter if it exists
    System.IO.Directory.CreateDirectory(directory);

    string fileName = filenameWithoutExtension + ".txt";
    string pathString = System.IO.Path.Combine(directory, fileName);

    using(System.IO.StreamWriter file = new System.IO.StreamWriter(pathString))
    {
        file.WriteLine(Some_Method(MP.Mwidth, MP.Mheight, MP.Mtype, "" )); 
    }
}

你也可以只使用File.WriteAllText或类似的方法来避免以这种方式创建文件。使用usingblock 保证文件将被关闭,即使Some_Method引发异常。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 文件处理 - 创建文件并打开 的相关文章

随机推荐