1

I am trying to upload a file to a folder in ASP.NET, so far I have gotten the file stream like so:

public void Upload()
        {
            foreach (string file in Request.Files)
            {
                var fileContent = Request.Files[file];
                if (fileContent != null && fileContent.ContentLength > 0)
                {
                    var stream = fileContent.InputStream;
                    var fileName = fileContent.FileName;
                    //you can do anything you want here
                }
            }

            foreach (string key in Request.Form)
            {
                var value = Request.Form[key];
            }
        }

I just dont know how to save it....Im soooooo tired.

user979331
  • 11,039
  • 73
  • 223
  • 418

3 Answers3

1

Have you tried StreamWriter?

using (StreamWriter sw = new StreamWriter(Server.MapPath("~/yourfile.txt"), true))
 {
     sw.WriteLine("lalala");
 }  
titol
  • 999
  • 13
  • 25
1

If you are using .Net 4 and above, then you can use Stream.CopyTo method

// Create the streams.
MemoryStream destination = new MemoryStream();

using (FileStream source = File.Open(@"c:\temp\data.dat",
    FileMode.Open))
{

    Console.WriteLine("Source length: {0}", source.Length.ToString());

    // Copy source to destination.
    source.CopyTo(destination);
}

You can use that in your code as below

public void Upload()
{
    foreach (string file in Request.Files)
    {
        var fileContent = Request.Files[file];
        if (fileContent != null && fileContent.ContentLength > 0)
        {
            var stream = fileContent.InputStream;
            var fileName = fileContent.FileName;
            //you can do anything you want here
            var path = Server.MapPath("~/SomeFolder")
            using (var newFile = File.Create(Path.Combine(path,fileName))
            {
                await stream.CopyTo(newFile);
            }
        }
    }

    foreach (string key in Request.Form)
    {
        var value = Request.Form[key];
    }
}
Kishore Kumar
  • 12,675
  • 27
  • 97
  • 154
1

Just create the file and copy from the source stream to the destination stream.

using (var file = File.Create(fileName))
{
    await stream.CopyToAsync(file);
}
Andrei Tătar
  • 7,872
  • 19
  • 37