Hi Adrian,
When arg = o (reading) and reading is done in a try/catch loop
the application will freeze, so I made a slight addition to your
solution, namely added a posting to a log file if arg = 0 and
the file doesn't exist. Should the situation arise, then it will
be easily rectified.
Try this for yourself - it works fine for me:
static void Main()
{
string path = @"c:\__delete_me.txt";
Console.WriteLine("Press [enter] to begin");
Console.ReadLine();
LockAsync(path, FileShare.None, 2000);
using (FileStream stream = OpenWhenReady(path, FileAccess.Read))
{
Console.WriteLine("File Opened: ");
Console.WriteLine();
StreamReader reader = new StreamReader(stream);
Console.WriteLine(reader.ReadToEnd());
}
Console.ReadLine();
}
private static void LockAsync(string path, FileShare share, int
milliseconds)
{
using (EventWaitHandle wait = new EventWaitHandle(false,
EventResetMode.ManualReset))
{
ThreadStart start = delegate()
{
using (FileStream stream = new FileStream(path,
FileMode.OpenOrCreate, FileAccess.Write, share))
{
wait.Set();
System.Threading.Thread.Sleep(milliseconds);
byte[] bytes = Encoding.ASCII.GetBytes(Environment.NewLine +
DateTime.Now.ToString());
stream.Seek(0, SeekOrigin.End);
stream.Write(bytes, 0, bytes.Length);
}
};
start.BeginInvoke(delegate(IAsyncResult result)
{
start.EndInvoke(result);
}, null);
wait.WaitOne();
}
}
public static FileStream OpenWhenReady(string path, FileAccess access)
{
FileStream stream = null;
do
{
try
{
stream = new FileStream(path, FileMode.OpenOrCreate, access);
}
catch (IOException)
{
Console.WriteLine("Waiting for Lock");
System.Threading.Thread.Sleep(500);
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Waiting for Lock");
System.Threading.Thread.Sleep(500);
}
}
while (stream == null);
return stream;
}
By the way are you able to solve my other little problem
that I posted concerning shifting the margin a bit to the left
in the print routine?, q.v. my posting if you have time.
Where is it posted?