C# 我如何从其路径获取文件输入流?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12671862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How would i get a file input stream from its path?
提问by Pomster
I have the path of a file i would like to upload but the method takes the file input Stream.
我有我想上传的文件的路径,但该方法采用文件输入流。
Can anyone tell me how i can get the input stream from the path?
谁能告诉我如何从路径中获取输入流?
I have upload files before when using a open file dialog and that takes the file in as a file input Stream, but the new section of my webpage the user does not select the file, i have to go grab it with code, but i know its file path.
我之前在使用打开文件对话框时上传了文件,并将文件作为文件输入流,但是我网页的新部分用户没有选择文件,我必须用代码抓取它,但我知道它的文件路径。
public string uploadfile(string token, string filenameP, DateTime modDate, HttpPostedFileBase file)
{
//... code to upload file
}
I would like something like the ClassLoader like in java.
我想要类似 Java 中的 ClassLoader 的东西。
See this question here.
在这里看到这个问题。
回答by Furqan Safdar
You can use StreamWrite or StreamReader class for this purpose:
为此,您可以使用 StreamWrite 或 StreamReader 类:
// for reading the file
using (StreamReader sr = new StreamReader(filenameP))
{
//...
}
// for writing the file
using (StreamWriter sw = new StreamWriter(filenameP))
{
//...
}
Reference: http://msdn.microsoft.com/en-us/library/f2ke0fzy.aspx
回答by george.zakaryan
public string uploadfile(string token, string filenameP, DateTime modDate, HttpPostedFileBase file)
{
using (StreamReader reader = new StreamReader(filenameP))
{
//read from file here
}
}
P.S. Don't forget to include System.IO namespace
PS 不要忘记包含 System.IO 命名空间
Edit: the stream manipulating classes in System.IO are wrapping Stream base class. reader.BaseStream property will give you that stream.
编辑:System.IO 中的流操作类正在包装 Stream 基类。reader.BaseStream 属性将为您提供该流。
回答by Mukul Goel
First open an input stream on your file
首先在您的文件上打开一个输入流
then pass that input stream to your upload method
然后将该输入流传递给您的上传方法
eg: to open stream on files
例如:打开文件流
// Character stream writing
StreamWriter writer = File.CreateText("c:\myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();
// Character stream reading
StreamReader reader = File.OpenText("c:\myfile.txt");
string line = reader.ReadLine();
while (line != null) {
Console.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();
回答by Wolfgang Grinfeld
In C#, the way to get a Stream (be it for input or for output): use a derived class from Stream, e.g. new FileStream(inputPath, FileMode.Open)
在 C# 中,获取 Stream 的方法(无论是用于输入还是用于输出):使用来自 Stream 的派生类,例如 new FileStream(inputPath, FileMode.Open)
回答by divay pandey
Use File.OpenRead(path)FileStream Class on Microsoft Docs
在 Microsoft Docs 上使用File.OpenRead(path)FileStream 类

