user3281649
user3281649

Reputation: 61

how to clear text file content c#

i want clear text file contet with this method

private void writeTextFile(string filePath, string text)
{
    if (!File.Exists(filePath))
    {
        File.Create(filePath).Close();

    }
    using (StreamWriter tw = new StreamWriter(filePath))
    {
        File.WriteAllText(filePath,"");
        tw.WriteLine(text);
        tw.Close();
    }
}

but i get this error

The process cannot access the file  because it is being used by another process.

but this not open in anywhere ,

please help me thank's

Upvotes: 5

Views: 56508

Answers (7)

Mr. Squirrel.Downy
Mr. Squirrel.Downy

Reputation: 1177

Why not use FileStream with FileMode.Create?

using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
    //Do something...
}

Look at the MSDN of FileMode Enum

Create
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.

Overwritten will cover/remove/clean/delete all existed file data.
if you would like to use StreamWriter, use new StreamWriter(fs).

Upvotes: 0

Swiler
Swiler

Reputation: 29

You only need to specify false in the second parameter of the constructor for StreamWriter( route, false )

String ruta = @"C:\Address\YourFile".txt";

using (StreamWriter file = new StreamWriter(ruta, false))
{
     for ( int i = 0; i < settings.Length; ++i )
         file.WriteLine( settings[ i ] );

     file.Close();
}

Upvotes: 1

RobertoFRey
RobertoFRey

Reputation: 734

// I decided to use this solution
// this section is to clear MyFile.txt
     using(StreamWriter sw = new StreamWriter(@"MyPath\MyFile.txt", false))
     {
       foreach(string line in listofnames)
       {
          sw.Write(""); // change WriteLine with Write
       }
        sw.Close();
      }
    // and this section is to copy file names to MyFile.txt
        using(StreamWriter file = new StreamWriter(@"MyPath\MyFile.txt", true))
        {
        foreach(string line in listofnames)
        {
            file.WriteLine(line);
        }
      }

Upvotes: 1

Albert Cosme Monteiro
Albert Cosme Monteiro

Reputation: 11

Assuming that your file already exists and you want to clear its contents before populating it or whatever, I found the best way to do this with StreamWriter is..

// this line does not create test.txt file, assuming that it already exists, it will remove the contents of test.txt 
Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(Path.GetFullPath(C:\test.txt), False)

// this line will now be inserted into your test.txt file
sw.Write("hey there!")

Upvotes: 1

Harsha Siriwardana
Harsha Siriwardana

Reputation: 172

You can use StreamWriter for creating a file for write and use Truncate to write with clearing previous content.

StreamWriter writeFile;
writeFile = new StreamWriter(new IsolatedStorageFileStream(filename, FileMode.Truncate, myIsolatedStorage));
writeFile.WriteLine("String");
writeFile.Close();

This use FileMode.Truncate

Truncate Specifies that an existing file it to be opened and then truncated so that its size is zero bytes.

Upvotes: 2

NucS
NucS

Reputation: 629

The problem is with you locking the file by initializing StreamWriter onto filePath and then trying to call File.WriteAllText which also internally attempts to lock the file and eventually end up with an exception being thrown.

Also from what it looks you are trying to clear the file's content and then write something in.
Consider the following:

private void writeTextFile(string filePath, string text) {
    using (StreamWriter tw = new StreamWriter(filePath, false))  //second parameter is `Append` and false means override content            
        tw.WriteLine(text);

}

Upvotes: 0

Codeman
Codeman

Reputation: 12375

That's because you're creating a StreamWriter, then using File.WriteAllText. Your File is already being accessed with the StreamWriter.

File.WriteAllText does just that, writes the entire string you pass to it to a file. StreamWriter is unnecessary if you're going to use File.WriterAllText.

If you don't care about overwriting an existing file, you can do this:

private void writeTextFile(string filePath, string text)
{
    File.WriteAllText(filePath, text);
}

If you want to use StreamWriter (which, by the way, File.WriteAllText uses, it just hides it), and append to the file, you can do this (from this answer):

using(StreamWriter sw = File.AppendText(path))
{
    tw.WriteLine(text);
}

Upvotes: 16

Related Questions