Sreejesh Kumar
Sreejesh Kumar

Reputation: 2499

Fetch files from folder

I have somes files in a folder. I want to fetch the files from that folder and convert each file to an object of binary stream and store in a collection. And from the collection, I want to retrieve each binary stream objects. How is it possible using ASP.Net with c# ?

Upvotes: 0

Views: 3807

Answers (3)

Bobby
Bobby

Reputation: 11576

It can be as simply as this:

using System;
using System.Collections.Generic;
using System.IO;

List<FileStream> files = new List<FileStream>();
foreach (string file in Directory.GetFiles("yourPath"))
{
    files.Add(new FileStream(file, FileMode.Open, FileAccess.ReadWrite));
}

But overall, storing FileStreams like this does not sound like a good idea and does beg for trouble. Filehandles are a limited resource in any operating system, so hocking them is not very nice nore clever. You would be better off accessing the files as needed instead of simply keeping them open at a whim.

So basically storing only the paths and accessing the files as needed might be a better option.

using System;
using System.Collections.Generic;
using System.IO;

List<String> files = new List<String>();
foreach (string file in Directory.GetFiles("yourPath"))
{
    files.Add(file);
}

Upvotes: 4

Adriaan Stander
Adriaan Stander

Reputation: 166346

If you wish to have it stored in a MemoryStream you could try

List<MemoryStream> list = new List<MemoryStream>();
string[] fileNames = Directory.GetFiles("Path");
for (int iFile = 0; iFile < fileNames.Length; iFile++)
{
    using (FileStream fs = new FileStream(fileNames[iFile], FileMode.Open))
    {
        byte[] b = new byte[fs.Length];
        fs.Read(b, 0, (int)fs.Length);
        list.Add(new MemoryStream(b));
    }
}

Or even use a Dictionary if you wish to keep the file names as keys

Dictionary<string, MemoryStream> files = new Dictionary<string, MemoryStream>();
string[] fileNames = Directory.GetFiles("Path");
for (int iFile = 0; iFile < fileNames.Length; iFile++)
{
    using (FileStream fs = new FileStream(fileNames[iFile], FileMode.Open))
    {
        byte[] b = new byte[fs.Length];
        fs.Read(b, 0, (int)fs.Length);
        files.Add(Path.GetFileName(fileNames[iFile]), new MemoryStream(b));
    }
}

Upvotes: 2

regex
regex

Reputation: 3601

This can be done using DirectoryInfo and FileInfo classes. Here is some code that should hopefully do what you need:

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"C:\TempDir\");
if (dir.Exists)
{
    foreach (System.IO.FileInfo fi in dir.GetFiles())
    {
        System.IO.StreamReader sr = new System.IO.StreamReader(fi.OpenRead());
        // do what you will....
        sr.Close();
    }
}

Upvotes: 0

Related Questions