code_junkie

How to open a file for non-exclusive write access using .NET

Nov 14th, 2011
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Threading;
  6.  
  7. namespace FileOpenTest
  8. {
  9. class Program
  10. {
  11. private static bool keepGoing = true;
  12.  
  13. static void Main(string[] args)
  14. {
  15. Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
  16.  
  17. Console.Write("Enter name: ");
  18. string name = Console.ReadLine();
  19. //Open the file in a shared write mode
  20. FileStream fs = new FileStream("file.txt",
  21. FileMode.OpenOrCreate,
  22. FileAccess.ReadWrite,
  23. FileShare.ReadWrite);
  24.  
  25. while (keepGoing)
  26. {
  27. AlmostGuaranteedAppend(name, fs);
  28. Console.WriteLine(name);
  29. Thread.Sleep(1000);
  30. }
  31.  
  32. fs.Close();
  33. fs.Dispose();
  34. }
  35.  
  36. private static void AlmostGuaranteedAppend(string stringToWrite, FileStream fs)
  37. {
  38. StreamWriter sw = new StreamWriter(fs);
  39.  
  40. //Force the file pointer to re-seek the end of the file.
  41. //THIS IS THE KEY TO KEEPING MULTIPLE PROCESSES FROM STOMPING
  42. //EACH OTHER WHEN WRITING TO A SHARED FILE.
  43. fs.Position = fs.Length;
  44.  
  45. //Note: there is a possible race condition between the above
  46. //and below lines of code. If a context switch happens right
  47. //here and the next process writes to the end of the common
  48. //file, then fs.Position will no longer point to the end of
  49. //the file and the next write will overwrite existing data.
  50. //For writing periodic logs where the chance of collision is
  51. //small, this should work.
  52.  
  53. sw.WriteLine(stringToWrite);
  54. sw.Flush();
  55. }
  56.  
  57. private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
  58. {
  59. keepGoing = false;
  60. }
  61. }
  62. }
  63.  
  64. new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
Add Comment
Please, Sign In to add comment