Aditya
Aditya

Reputation: 65

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.

After writing into file I am attaching it in mail(using smtp client to send mails)

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.

Upvotes: 1

Views: 1795

Answers (6)

Samarth Mehta
Samarth Mehta

Reputation: 21

Try This one

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

Upvotes: 1

Nguyen Van Thanh
Nguyen Van Thanh

Reputation: 825

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

Upvotes: 3

Gauravsa
Gauravsa

Reputation: 6528

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.

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

        }
    }

Upvotes: 0

Burak Koçyiğit
Burak Koçyiğit

Reputation: 82

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

Upvotes: 1

Aditya
Aditya

Reputation: 65

The problem was with MailMessage instance, it was keeping file open.Disposing mail messaging instance worked for me.

mail.Dispose();

Upvotes: 1

BJ Coder
BJ Coder

Reputation: 402

Try this solution, it might helpful

using (StreamWriter stream = new StreamWriter(attachment, false))
        {
            stream.WriteLine("some text here");
        }

Upvotes: 2

Related Questions