File txt

close a txt file

Page 1 of 1

3 Replies - 1785 Views - Last Post: 26 September 2008 - 09:08 AM Rate Topic: -----

#1 Benetz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 09-September 08

File txt

Posted 26 September 2008 - 06:53 AM

hello! i'm working in a project where i must work with txt file...

but when i do this operation Visual give me the seguent error:

The process can not access the file 'C: \ .... \ Desktop \ myfile.txt' because it is in use by another process.

this is my procedure:

if (!System.IO.File.Exists(FilePath)) System.IO.File.Create(FilePath);
System.IO.File.WriteAllText(FilePath, "stringToWrite"); <-- . Visual Studio indicates to me the error in this line




there is some way to solve? thank you very much at all!

Is This A Good Question/Topic? 0
  • +

Replies To: File txt

#2 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1385
  • View blog
  • Posts: 10,962
  • Joined: 06-February 08

Re: File txt

Posted 26 September 2008 - 07:10 AM

The problem is that you're still creating the file when you try to write to it.

Make it sleep a little after creating the file, this way, it will have finished creating it by the time you write to it:
if (!System.IO.File.Exists(FilePath))
{
    System.IO.FIle.Create(FilePath);
    System.Threading.Thread.Sleep(500); // wait until it's made
}
System.IO.File.WriteAllText(FilePath, stringToWrite);

Hope this helps :)
Was This Post Helpful? 0
  • +
  • -

#3 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: File txt

Posted 26 September 2008 - 07:39 AM

Actually that happens because Create() has created the file and is still holding on to it. If you're using WriteAllText you dont need to use Create as this will create the file for you (if it doesnt already exist). Look at this example

//check to make sure the file doesn't exist
if (!(System.IO.File.Exists(FilePath)))
{
      //it doesn't exist so create and write the text
   System.IO.File.WriteAllText(FilePath, stringToWrite);
}
else
{
      //file exists we we just append the text
      System.IO.File.AppendAllText(FilePath, stringToWrite);
}




So, as you can see, WriteAllText will actually create your text file if it doesn't already exist
Was This Post Helpful? 0
  • +
  • -

#4 Benetz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 09-September 08

Re: File txt

Posted 26 September 2008 - 09:08 AM

Thanks guys, now here are the six on Friday and now I go home to eat ... this evening i'll try it..and I will tell you if it works ... thanks again!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1