5

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

user3281649
  • 61
  • 1
  • 1
  • 3

7 Answers7

16

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);
}
Community
  • 1
  • 1
Codeman
  • 12,157
  • 10
  • 53
  • 91
  • 2
    Or at that point just delete the method entirely and have the caller call `File.WriteAllText` directly, because this method accomplishes nothing. – Servy Feb 14 '14 at 22:23
  • @Servy yup! I was just going with the existing template. – Codeman Feb 14 '14 at 22:23
2

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.

1

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!")
1
// 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);
        }
      }
RobertoFRey
  • 674
  • 1
  • 5
  • 10
1

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();
}
The Muffin Man
  • 19,585
  • 30
  • 119
  • 191
Swiler
  • 29
  • 6
0

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

}
NucS
  • 619
  • 8
  • 21
  • I think the second parameter is not append, but rather the encoding. – Satbir Kira Jun 12 '15 at 08:41
  • 1
    There are two constructors, one with encoding as second param and another one with boolean as second param. https://msdn.microsoft.com/en-us/library/system.io.streamwriter(v=vs.110).aspx – NucS Jun 25 '15 at 13:59
0

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).