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 bina开发者_如何学Gory stream objects. How is it possible using ASP.Net with c# ?
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 FileStream
s 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);
}
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));
}
}
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();
}
}
精彩评论