Advertisement
Guest User

Untitled

a guest
Feb 2nd, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 KB | None | 0 0
  1. //In WCF service
  2. FileStream fs = null;
  3. public void AppendBytes(string fileName, byte[] data, long position)
  4. {
  5. try
  6. {
  7. if (fs==null)//In first call, open the file handle
  8. fs = System.IO.File.Open(fileName, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None);
  9.  
  10. fs.Write(data, 0, data.Length);
  11. }
  12. catch (Exception ex)
  13. {
  14. //Close handle in case of error
  15. if (fs != null)
  16. fs.Close();
  17. }
  18. }
  19.  
  20. public void CloseHandle()
  21. {
  22. //Close handle explicitly
  23. if (fs != null)
  24. fs.Close();
  25. }
  26.  
  27. public void DoSomeOperation(string fileName)
  28. {
  29. using (FileStream fsO = System.IO.File.Open(fileName, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None))
  30. {
  31. //Do something with file here, this is atomic operation so I am opening FileStream with 'using' to dispose at operation is over
  32. }
  33. }
  34.  
  35. //In client
  36. public void CallerFunction()
  37. {
  38. //Read Data from sourceFile in chunk and copy to target file using WCF.AppendBytes on another machine
  39. WCF.AppendBytes(filename, data, pos);
  40. WCF.CloseHandle();
  41. WCF.DoSomeOperation(filename); //I get error here that file is in use with some other process. if I put a thread.sleep(1000) just before this statement then all works fine.
  42. }
  43.  
  44. static void TestHandleClose()
  45. {
  46. int i = 0;
  47. try
  48. {
  49.  
  50. if (File.Exists(@"d:destinationfile2.exe"))
  51. File.Delete(@"d:destinationfile2.exe");
  52.  
  53. byte[] data = null;
  54. int blocksize = 10 * 1024 * 1024;
  55.  
  56. for( i=0;i<100;i++)
  57. {
  58. using (FileStream fr = File.Open(@"d:destinationFile1.zip", FileMode.Open, FileAccess.Read, FileShare.None))
  59. {
  60. data = new byte[blocksize];
  61. fr.Read(data, 0, blocksize); //We are reading the file single time but appending same data to target file multiple time.
  62.  
  63. using (FileStream f = File.Open(@"d:destinationfile2.exe", FileMode.Append, FileAccess.Write, FileShare.None))
  64. {
  65. f.Write(data, 0, data.Length); //We are writing same data multiple times.
  66. f.Flush();
  67. f.Close();
  68. }
  69. }
  70.  
  71. }
  72.  
  73. if (File.Exists(@"d:destinationfile2.exe"))
  74. File.Delete(@"d:destinationfile2.exe");
  75.  
  76. }
  77. catch (Exception ex)
  78. {
  79. throw;
  80. }
  81. }
  82.  
  83. using (FileStream fileStream = new FileStream(file, mode, access, FileShare.ReadWrite))
  84. {...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement