首页 > 解决方案 > 我收到“该进程无法访问该文件,因为它正被另一个进程使用”错误。有任何想法吗?

问题描述

所以,我在 AppData 中创建了一个文件和一个 txt 文件,我想覆盖 txt。但是当我尝试这样做时,它一直给我这个错误。有任何想法吗?

            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string setuppath = (path + "\\");
            string nsetuppath = (setuppath + "newx" + "\\");
            Directory.CreateDirectory(nsetuppath);

            string hedef2 = (nsetuppath + "commands.txt");
            File.Create(hedef2);
            StreamWriter sw = new StreamWriter(hedef2);   ----> This is where the error appears.
            sw.WriteLine("Testtest");

标签: c#

解决方案


使用流时只需使用该using语句。当使用它的代码完成时,using 语句会自动调用对象上的 Dispose。

        //path to the file you want to create
        string path = @"C:\code\Test.txt";
        // Create the file, or overwrite if the file exists.
        using (FileStream fs = File.Create(path))
        {
            byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

有很多操作流的方法,根据您的需要保持简单


推荐阅读