Reputation: 1213
System.IO.File.CreateText(@"C:\\ProgramData\\Password Manager\\pwd.dat");
This makes the file perfectly.
System.IO.File.WriteAllLines(@"C:\\ProgramData\\Password Manager\\pwd.dat", pwd);
But this line gets an error
"The process cannot access the file 'C:\ProgramData\Password Manager\pwd.dat' because it is being used by another process."
Is there a way to close the file before writing to it?
Upvotes: 0
Views: 462
Reputation: 216363
File.CreateText not only create the file, but open it and returns a stream to write the file.
Your subsequent call finds the file blocked by yourself
Try
StreamWriter sw = File.CreateText(@"C:\\ProgramData\\Password Manager\\pwd.dat");
sw.Close();
sw.Dispose();
or simply
using(File.CreateText(@"C:\\ProgramData\\Password Manager\\pwd.dat")) {}
(The using statement takes care to close and dispose the file)
however, this is completely unnecessary seeing your code because File.WriteAllLines creates the file if it doesn't exist.
Upvotes: 4
Reputation: 69372
You don't need to use CreateText
. Simply call WriteAllLines
and that will create the file for you. At the moment the stream returned by CreateText
is holding onto the file it created which is the reason why the error is thrown.
Upvotes: 4