Labels:

If the file is locked by the process exclusively, it is not possible to open those files. But if the process holds only shared lock, we can open the file using c# using the following code,

FileStream objf = new FileStream(”Ouput.xls”, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

Excel hold the shared lock on the files.

The Following is an example program to read a file,



  1. using System.IO;

  2. public static byte[] ReadFile(string filePath)
  3. {
  4. byte[] buffer;
  5. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  6. try
  7. {
  8. int length = (int)fileStream.Length; // get file length
  9. buffer = new byte[length]; // create buffer
  10. int count; // actual number of bytes read
  11. int sum = 0; // total number of bytes read

  12. // read until Read method returns 0 (end of the stream has been reached)
  13. while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
  14. sum += count; // sum is a buffer offset for next reading
  15. }
  16. finally
  17. {
  18. fileStream.Close();
  19. }
  20. return buffer;
  21. }


Comments (0)

Post a Comment