问题
I need to temporary store a file upload to a MemoryStream.
What would be the best method to do this using asp.net (3.5)?
Here's what I have so far. It works (locally tested), but it does not look right to me.
protected void lnkUploadFile_Click(object sender, EventArgs e)
{
MemoryStream memStream = new MemoryStream();
BinaryWriter sWriter = new BinaryWriter(memStream);
foreach (byte b in flUpload.FileBytes)
{
sWriter.Write(b);
}
sWriter.Flush();
// writing to file to verify file stream converted correctly
FileStream fstream = new FileStream(@"C:/test/" + flUpload.FileName, FileMode.Create);
memStream.WriteTo(fstream);
fstream.Dispose();
memStream.Dispose();
}
回答1:
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());
回答2:
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);
}
}
}
回答3:
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");
回答4:
Just three lines.
if (flUpload.FileName.Length > 0)
{
string directoryPath="C:\\SomeFolderName";
flUpload.SaveAs(directoryPath + "\\" + fileUpload.FileName);
}
来源:https://stackoverflow.com/questions/1690337/what-is-the-best-practice-for-storing-a-file-upload-to-a-memorystream-c