What is the best practice for storing a file upload to a MemoryStream (C#)?

回眸只為那壹抹淺笑 提交于 2019-12-04 18:13:59

If flUpload.FileBytes is a byte array, you can use the MemoryStream constructor that accepts the contained data as a parameter:

MemoryStream memStream = new MemoryStream(flUpload.FileBytes);

If not (if it just implements IEnumerable), you can convert it to a byte array using Linq:

MemoryStream memStream = new MemoryStream(flUpload.FileBytes.ToArray());
    protected void lnkUploadFile_Click(object sender, EventArgs e)
    {
        using (MemoryStream memStream = new MemoryStream(flUpload.FileBytes))
        {
            using (FileStream fstream = new FileStream(@"C:/test/" + 
                flUpload.FileName, FileMode.Create))
            {
                memStream.WriteTo(fstream);
            }
        }
    }

Might be easier to work with as a string... all depends on what you're going to do with it I guess.

System.IO.StreamReader reader = new System.IO.StreamReader("path");
string file = reader.ReadToEnd();

Or if you need the bytes there is actually a code snipet "filReadBin" you can use that produces this:

byte[] fileContents;
fileContents = System.IO.File.ReadAllBytes(@"C:\Test.txt");
Mayank Kukadia

Just three lines.

if (flUpload.FileName.Length > 0)
{
   string directoryPath="C:\\SomeFolderName";
   flUpload.SaveAs(directoryPath + "\\" + fileUpload.FileName);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!