首页 > 解决方案 > 为什么我得到另一个进程错误使用的文件?

问题描述

当我调用该Generate函数时,它不会创建StreamWriter对象,而是抛出一个异常:

另一个进程使用的文件

但文件未打开,这是第一个使用它的 Stream。

    public static string GetWindowsUserName()
    {
        string st = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
        bool Condition = false;
        foreach (char ch in st)
        {
            if (ch == '\\')
                Condition = true;
        }
        if (Condition)
        {
            string[] stArr = st.Split('\\');
            st = stArr[stArr.Length - 1];
        }
        return st;
    }
    public static void Generate(bool Desktop, bool RemoveLast, bool InExistingTxt, int Count, int Length)
    {
        Random Generator = new Random();
        if (Desktop)
            path = $"C:\\Users\\{GetWindowsUserName()}\\Desktop\\GeneratedNumbers.txt";
        else
            path = "GeneratedNumbers.txt";
        if (!InExistingTxt && !RemoveLast)
            File.Create(path);
        else if (!InExistingTxt && RemoveLast)
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            File.Create(path);
        }
        System.Threading.Thread.Sleep(1000);
        if (File.Exists(path))
        {
            StreamWriter SW = new StreamWriter(path);
            for (int i = 0; i < Count; i++)
            {
                string st = "";
                for (int j = 0; j < Length; j++)
                {
                    int o = Generator.Next(0, 11);
                    st += Convert.ToString(o);
                }
                SW.WriteLine(st);
            }
            SW.Dispose();
        }
    }

标签: c#.netstreamwriter

解决方案


File.Create将流返回到创建的文件。由于您没有处理流,因此在尝试重新打开同一个文件时会出错。

我还怀疑您搞砸了“RemoveLast”逻辑。我假设您想在设置为 false 时将内容附加到现有文件:

if (InExistingTxt && !File.Exists(path))
    return;

StreamWriter SW;

if (RemoveLast)
    SW = File.CreateText(path);
else 
    SW = File.AppendText(path);

using (SW)
{
    for (int i = 0; i < Count; i++)
    {
        string st = "";
        for (int j = 0; j < Length; j++)
        {
            int o = Generator.Next(0, 11);
            st += Convert.ToString(o);
        }
        SW.WriteLine(st);
    }
}

推荐阅读