C# 如何将附件保存到文件夹? .净2.
本文关键字:文件夹 保存 | 更新日期: 2023-09-27 18:32:39
我正在创建一个csv文件并将其附加到像这样的电子邮件中...
using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv)))
{
try
{
to = "email@email.com";
string from = "user@email.co.uk";
string subject = "Order p"+ OrderNumber;
string body = result;
SmtpClient SMTPServer = new SmtpClient("127.0.0.1");
MailMessage mailObj = new MailMessage(from, to, subject, body);
Attachment attachment = new Attachment(stream, new ContentType("text/csv"));
attachment.Name = "p" + OrderNo + "_" + CustomerReference+".csv";
mailObj.Attachments.Add(attachment);
SMTPServer.Send(mailObj);
}
catch (Exception ex)
{ }
}
这工作正常,但是如何将相同的csv文件保存到文件夹中?谢谢
System.IO 中的File.WriteAllText
方法可能是实现此目的的最简单方法:
File.WriteAllText("<destination>", csv);
其中<destination>
是要将 CSV 保存到的文件的路径。如果此文件尚不存在,则将创建该文件,否则将被覆盖。
您必须将流保存到某个位置:
var newfile = new StreamWriter(path_filename);
foreach (var l in stream)
newfile.WriteLine(l);
newfile.Close();
编辑:
请改用这个:
StreamWriter outputfile = new StreamWriter("c:'temp'outputfile.csv");
然后是 foreach 循环。
已编辑 2(来自 msdn 站点):
// Read the first 20 bytes from the stream.
byteArray = new byte[memStream.Length];
count = memStream.Read(byteArray, 0, 20);
// Read the remaining bytes, byte by byte.
while(count < memStream.Length)
{
byteArray[count++] =
Convert.ToByte(memStream.ReadByte());
}
// Decode the byte array into a char array
// and write it to the console.
charArray = new char[uniEncoding.GetCharCount(
byteArray, 0, count)];
uniEncoding.GetDecoder().GetChars(
byteArray, 0, count, charArray, 0);
Console.WriteLine(charArray); //here you should send to the file as the first example i wrote instead of to writing to console.