neel
neel

Reputation: 5293

Issue in create and write in a text file using c#

I try to create a text file and write some data to it. I am using the following code:

public void AddNews(string path,string News_Title,string New_Desc)
{
    FileStream fs = null;
    string fileloc = path + News_Title+".txt";
    if (!File.Exists(fileloc))
    {
        using (fs = new FileStream(fileloc,FileMode.OpenOrCreate,FileAccess.Write))
        {               
            using (StreamWriter sw = new StreamWriter(fileloc))
            {
                sw.Write(New_Desc);           
            }
        }
    }
}

I got this exception in stream writer:

The process cannot access the file '..............\Pro\Content\News\AllNews\Par.txt'
because it is being used by another process.

Text file is created, but I can't write to it.

Upvotes: 1

Views: 727

Answers (4)

gpmurthy
gpmurthy

Reputation: 2427

The issue could be that the file is open or in use. Consider checking if the file is open before writing to it:

public bool IsFileOpen(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        // Is Open
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //Not Open
    return false;
}

Upvotes: 0

Julián Urbano
Julián Urbano

Reputation: 8488

I would simply do this:

public void AddNews(string path, string News_Title, string New_Desc)
{
    string fileloc = Path.Combine(path, News_Title+".txt");
    if (!File.Exists(fileloc)) {
        File.WriteAllText(fileloc, New_Desc);           
    }
}

Note that I use Path.Combine as a better way to create paths, and File.WriteAllText as a simple way of creating a file and writing something to it. As MSDN says:

If the target file already exists, it is overwritten.

so we first check if the file already exists, as you did. If you want to overwrite its contents, just don't check and write directly.

Upvotes: 1

SpiderCode
SpiderCode

Reputation: 10122

using (TextWriter tw = new StreamWriter(path, true))
{
  tw.WriteLine("The next line!");
}

Upvotes: 0

Robert Harvey
Robert Harvey

Reputation: 180787

When you create your StreamWriter object, you're specifying the same file that you already opened as a FileStream.

Use the constructor overload of StreamWriter that accepts your FileStream object, instead of specifying the file again, like this:

using (StreamWriter sw = new StreamWriter(fs))

Upvotes: 2

Related Questions