6

I have a path which has a list of files.

foreach (var file in Directory.GetFiles(networkpath))
{
  Stream s=file.
} 

I want to convert the file into Stream.How to proceed further?

2
  • What kind of stream do you need? Oct 5, 2015 at 19:06
  • Thanks everyone for your help ,got what i wanted. Oct 5, 2015 at 19:19

3 Answers 3

7

Is this what you need?

foreach (var file in Directory.GetFiles(networkpath))
{
    using (FileStream fs = File.Open(file, FileMode.Open))
    {

    }
}
0
2

You can safely read file using FileStream in C#. To be sure the whole file is correctly read, you should call FileStream.Read method in a loop, even if in the most cases the whole file is read in a single call of FileStream.Read method.

First create FileStream to open a file for reading. Then call FileStream.Read in a loop until the whole file is read. Finally close the stream.

using System.IO;

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

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

Change your file path to suit your code!Add this inside your loop!

FileStream fStream = new FileStream(@"c:\file.txt", FileMode.Open);
try
 {
  // read from file or write to file
 }
finally
 {
   fStream.Close();
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.