尝试此解决方案,可能会有所帮助
using (StreamWriter stream = new StreamWriter(attachment,false))
{
stream.WriteLine("some text here");
}
,
问题出在MailMessage实例上,它使文件保持打开状态。处理邮件实例对我有用。
mail.Dispose();
,
string directory = Application.StartupPath + @"\Data Base";//create this folder
string fileName = "write here file name" + ".dat";//you can change type of file like .txt
string memoryPath = Path.Combine(directory,fileName);
using (StreamWriter sw = File.CreateText(memoryPath))
{
sw.WriteLine("write here what you want");
}
,
使用此方法:
private bool WriteToDisk(string content,string filePath)
{
using (FileStream sw = new FileStream(filePath,FileMode.Append,FileAccess.Write,FileShare.ReadWrite))
{
byte[] infos = Encoding.UTF8.GetBytes(content);
sw.Write(infos,infos.Length);
}
return true;
}
通知:如果您的文件不存在,请使用以下命令创建:
private static void CreateFileIfNotExist(string filePath)
{
if (!File.Exists(filePath))
{
var folderPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
File.Create(filePath).Dispose();
}
,
尝试这个
using (StreamWriter str = new StreamWriter(attachment,false))
{
str.WriteLine("Heyy!! How are you");
}
,
为避免锁定问题,可以使用诸如对象或ReaderWriter之类的锁:
另外,可以使用File.AppendAllText或FileStream和StreamWriter代替
AppendAllLines。
public static var lock = new ReaderWriterLock();
public static void WriteToFile(string text)
{
try
{
string fileName = "";
lock.AcquireWriterLock(int.MaxValue);
File.AppendAllLines(fileName);
}
finally
{
lock.ReleaseWriterLock();
}
}
本文链接:https://www.f2er.com/2858893.html