我正在尝试通过c#
中的浏览按钮为我的电子邮件添加附件这是我的代码:
string fileName = Path.Combine(Path.GetTempPath(),FileUploadControl.FileName);
using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read))
{
byte[] buffer = new byte[1024];
int bytesRead; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
Attachment attachment = new Attachment(fileName);
msg.Attachments.Add(attachment);
$ exception {“Stream不支持读取。”} System.Exception {System.NotSupportedException}
我做错了什么?
答案 0 :(得分:1)
我的印象是FileUpload.FileName返回客户端端的文件名,而不是服务器端。您可能需要FileUpload.FileBytes,这是一个byte []数组。
string fileName = Path.Combine(Path.GetTempPath(),FileUploadControl.FileName);
using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(FileUploadControl.FileBytes, 0, FileUploadControl.FileBytes.Length);
}
Attachment attachment = new Attachment(fileName);
msg.Attachments.Add(attachment);
答案 1 :(得分:0)
您正在从同一个文件中读取和写入。请查看http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.saveas.aspx
上的示例答案 2 :(得分:0)
你很亲密。您打算从文件输入流中读取但不是:
string fileName = Path.Combine(Path.GetTempPath(),FileUploadControl.FileName);
using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read))
{
byte[] buffer = new byte[1024];
int bytesRead; while ((bytesRead = FileUploadControl.PostedFile.InputStream.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
Attachment attachment = new Attachment(fileName);
msg.Attachments.Add(attachment);
答案 3 :(得分:-2)
Attachment attachment = new Attachment(FileUploadControl.FileName);
msg.Attachments.Add(attachment);
就是你所需要的一切。