code_junkie

In C#, if 2 processes are reading and writing to the same file, what is the best way to avoid process locking exceptions?

Nov 11th, 2011
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
  2. {
  3. using (TextReader tr = new StreamReader(fileStream))
  4. {
  5. string fileContents = tr.ReadToEnd();
  6. }
  7. }
  8.  
  9. using (TextWriter tw = new StreamWriter(fileName))
  10. {
  11. tw.Write(fileContents);
  12. tw.Close();
  13. }
  14.  
  15. using (FileStream stream = new FileStream(@"C:Myfile.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
  16. {
  17. // Do your writing here.
  18. }
  19.  
  20. using (FileStream stream = new FileStream(@"C:Myfile.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  21. {
  22. // Does reading here.
  23. }
  24.  
  25. using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
  26. {
  27. using (TextReader tr = new StreamReader(fileStream))
  28. {
  29. string fileContents = tr.ReadToEnd();
  30. }
  31. }
  32.  
  33. FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
  34. using (TextWriter tw = new StreamWriter(fileStream))
  35. {
  36. tw.Write(fileContents);
  37. tw.Close();
  38. }
  39.  
  40. if (!info.Exists)
  41. return 0;
  42.  
  43. return (double)info.Length;
  44. }
Add Comment
Please, Sign In to add comment