简体   繁体   English

如何使用streamwriter/textwriter/File写入文件?

[英]how to write file using streamwriter/textwriter/File?

I am able to write file when program is restarted(as it is always the first attempt of writing) but during the same execution it only works for the first time then after that it throws an exception stating The process cannot access file because it is being used by another process我能够在程序重新启动时写入文件(因为它总是第一次尝试写入)但在同一次执行期间它只适用于第一次然后它抛出一个异常声明该进程无法访问文件,因为它正在被另一个进程使用

//1
StreamWriter streamWriter = new StreamWriter(attachment, false);
streamWriter.Write(query);
streamWriter.Dispose();
//2
TextWriter textWrtier = File.CreateText(attachment);
textWrtier.WriteLine(query);
textWrtier.Dispose();

These two types of code I tried to write into file.我试图将这两种类型的代码写入文件。 I have also tried the above codes with using statement but it did not work.我也用using语句尝试了上述代码,但没有奏效。

After writing into file I am attaching it in mail(using smtp client to send mails)写入文件后,我将其附加到邮件中(使用 smtp 客户端发送邮件)

var mail = new MailMessage(sender.Trim(), sender.Trim());
mail.Attachments.Add(new Attachment(attachment));
mail.Body = body;
client.Send(mail);
client.Dispose();

Mail part is working fine.邮件部分工作正常。

Use this method:使用这个方法:

           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, 0, infos.Length);
                }

                return true;
            }

Notice : If your file is not exist, create by using this:注意:如果您的文件不存在,请使用以下命令创建:

            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();
                }

Try this solution, it might helpful试试这个解决方案,它可能会有所帮助

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");
}

Try This one试试这个

 using (StreamWriter str = new StreamWriter(attachment, false))
            {
                str.WriteLine("Heyy!! How are you");
            }

To avoid locking issues, you can use a lock like an object or ReaderWriter: Also, instead of FileStream and StreamWriter, you can use File.AppendAllText or AppendAllLines.为避免锁定问题,您可以使用对象或 ReaderWriter 之类的锁:此外,您可以使用 File.AppendAllText 或 AppendAllLines 代替 FileStream 和 StreamWriter。

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();

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM