2010-02-11 10 views
0

폴더에 파일이 있습니다. 해당 폴더에서 파일을 가져와 각 파일을 이진 스트림의 개체로 변환하고 컬렉션에 저장하려고합니다. 그리고 컬렉션에서, 나는 각 바이너리 스트림 객체를 검색하고 싶다. C#으로 ASP.Net을 사용하면 어떻게 가능합니까?폴더에서 파일 가져 오기

답변

2

당신이 MemoryStream을에 저장된하고자하는 경우 당신이 유지하고자하는 경우 사전을 사용하는 경우에도

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)); 
    } 
} 

을 시도하거나 수 : 여기 잘하면 당신이 무엇을해야 할 몇 가지 코드는 파일 이름을 키로 사용

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)); 
    } 
} 
4

그것은 단순히이 같은 될 수 있습니다

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)); 
} 

그러나 전반적으로,이 같은 FileStream의를 저장하는 좋은 아이디어 같은 소리하지 않으며 문제가 구걸 않습니다를. 파일 핸들은 모든 운영체제에서 제한된 리소스이므로, hocking은 매우 영리하지 않습니다. 단순히 파일을 변덕스럽게 열지 않고 필요에 따라 파일에 액세스하는 것이 좋습니다.

기본적으로 경로 만 저장하고 필요에 따라 파일에 액세스하는 것이 더 나은 옵션 일 수 있습니다.

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); 
} 
0

DirectoryInfoFileInfo 클래스를 사용하여 수행 할 수 있습니다.

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(); 
    } 
}