Search code examples
c#.netstreamwriter

Why am I getting the file used by another process error?


When I call the Generate function it doesn't Create the StreamWriter object and instead throws an exception that says :

file used by another process

but the file isn't open and this is the first Stream that is using it.

    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();
        }
    }

Solution

  • File.Create returns a stream to the created file. Since you're not disposing the stream, you have an error when trying to re-open the same file.

    I also suspect that you messed up your "RemoveLast" logic. I'll assume that you want to append content to the existing file when it's set to 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);
        }
    }