Reputation: 11
My project: I am creating a nightly test system for machine vision systems. I want to be able to see real time results instead of waiting for all the tests to finish. Our old system was written in C++ and can access log files using notepad or any text editor for viewing (.txt) while they are being written to.
How am I doing this: A coworker years ago made a log file writing class that a ton of our applications use. I tried to use the dll from this class and everything works great. But, if I try to open one of the log files while the application is using it I get an access violation error: File is in use by another process.
How did I make it work: I simply copied the class from the other project and pasted it into my project's namespace. This solves the problem.
My question: Why does this work, but not when I use a reference to the dll? I would like to "fix" or "update" the Logging class that everyone in my department uses so my coworkers can enjoy this added functionality as well in our C# applications.
OS: Win 7 32-bit/Win XP/ Visual Studio 2005 and Visual Studio 2010.
Code of how we create the files is below and we use streamwriters to write to the files.
Any help would be greatly appreciated.
Thanks in advance, B
/// <summary>
/// Creates a file with the given file name or else uses the defualt.
/// </summary>
/// <param name="fileName">Name of file to create, if null use default.</param>
/// <param name="append">Whether to append to file if it already exists</param>
/// <returns>StreamWriter to the created file.</returns>
private StreamWriter CreateFile(string fileName, bool append)
{
FileStream fsOut;
StreamWriter sw;
if (append)
{
//sw = File.AppendText(fileName);
//just a note I tried many different modifiers of the FileAccess property and nothing seemed to work.
fsOut = File.Open(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
}
else
{
//sw = new StreamWriter(fileName);
fsOut = File.Create(fileName);
}
sw = new StreamWriter(fsOut);
sw.AutoFlush = true;
return sw;
}
Upvotes: 1
Views: 1626
Reputation: 100547
fsOut = File.Create(fileName);
will open file in non-shareable mode. So I suspect your "solution" has not much to do with copying code, but rather with happening to hit "append" code path instead of new.
Both processes should be opening file with compatible FileShare flags, so make sure you never open log files with default "share-none" flags.
Upvotes: 3