Pomster
Pomster

Reputation: 15197

How would I get a file input stream from its path?

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.

See this question here.

https://stackoverflow.com/a/793216/1479146

Upvotes: 14

Views: 93812

Answers (5)

divay pandey
divay pandey

Reputation: 349

Use File.OpenRead(path) FileStream Class on Microsoft Docs

Upvotes: 14

Wolfgang Grinfeld
Wolfgang Grinfeld

Reputation: 389

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)

Upvotes: 4

george.zakaryan
george.zakaryan

Reputation: 980

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

Edit: the stream manipulating classes in System.IO are wrapping Stream base class. reader.BaseStream property will give you that stream.

Upvotes: 2

Mukul Goel
Mukul Goel

Reputation: 8467

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

Upvotes: 0

Furqan Safdar
Furqan Safdar

Reputation: 16708

You can use StreamWrite or StreamReader class for this purpose:

// 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

Upvotes: 12

Related Questions