简体   繁体   中英

C# can not write to file (“being used by another process”)?

I was hoping someone could explain to me why this is happening :)

When I use the code below it gives me the error "The process cannot access the file 'C:\\test.txt' because it is being used by another process."

I'm very new to C# so I'm not sure what is going on, thanks in advance!

String fileNameBefore = @"C:\\test.txt";

public void output(String hex)
{
    using (StreamWriter writer = new StreamWriter(fileNameBefore, true))
    {
        writer.Write(hex);
        writer.Close();
    }
}

Close the text file before you write to it. (Not in code...physically close the text file)

Under Windows Vista and Windows 7 the root of the system volume (usually C:) has a special protection: Programs have to run with full admin privileges to do anything other than creating or deleting non-system folders. Programs aren't allowed to create files there. Why it's saying the file is in use by another process? I'd expect another message, but I guess that's indeed the reason... Unless you've got some other program having that file opened and sufficient rights on the program whose code we see above.

Make sure the process is properly closed by checking in windows task manager and look for your process name, and if you find any end the processes manually by clicking the end process button and try it again.

If that doesn't work try moving the file path to a writable area such as the desktop because as mario says the root has a protection.

also check that the file is not hidden or write protected

Hope this helps regards Tom

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM