我有一个包含文件列表的路径。
foreach (var file in Directory.GetFiles(networkpath))
{
Stream s=file.
}
我想将文件转换为Stream.How继续进行?
答案 0 :(得分:2)
这是你需要的吗?
foreach (var file in Directory.GetFiles(networkpath))
{
using (FileStream fs = File.Open(file, FileMode.Open))
{
}
}
答案 1 :(得分:1)
您可以使用C#中的FileStream安全地读取文件。为了确保正确读取整个文件,您应该在循环中调用FileStream.Read方法,即使在大多数情况下,只需要在FileStream.Read方法的单个调用中读取整个文件。
首先创建FileStream以打开文件进行读取。然后在循环中调用FileStream.Read,直到读取整个文件。最后关闭流。
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;
}
答案 2 :(得分:0)
更改您的文件路径以适合您的代码!在循环中添加它!
FileStream fStream = new FileStream(@"c:\file.txt", FileMode.Open);
try
{
// read from file or write to file
}
finally
{
fStream.Close();
}