Error The process cannot access the file because This file is being used by another process. What I need is to develop a class file, to provide the ability to add to its end. Actually it is a code with Form.

if (match.Success) ; else throw new IOException(" Неверный формат имени файла."); File file1 = new File(file_Name, text); file1.Add(file_Name, text); file1.get_Info(textBox1); ... catch (Exception ex)// тут ошибка, если обработку оставить 

Now the File class

  public File (string f_Name, string info) if (f_Name != null && info != null) if (System.IO.File.Exists(f_Name)) FileInfo exist_File = new FileInfo(f_Name); //Заполняем поля else System.IO.File.Create(f_Name); FileInfo create_File = new FileInfo(f_Name); //Заполняем поля 

Here, that above I have some problems with the logic of the program, at the same time you can tell.

  public void Add(string f_name,string new_text) { ошибка тут, если без try ... catch using (StreamWriter f_Stream = new StreamWriter(f_name, true, System.Text.Encoding.Default)) { byte[] array = System.Text.Encoding.Default.GetBytes(new_text); //int temp_Length = Convert.ToInt32(Length); //Length += array.Length; f_Stream.Write(new_text); Information += Environment.NewLine + new_text; 

What is wrong: 1) If a file with the same name is not created, an error occurs (see the header), but the file is created, adding to it is possible (from another button). 2) If the file already exists, then everything is fine, we add a line to the end of the file and output information on it.

What cant?

  • The jamb, most likely in your File class (in general, to make your own class, which is called just like a library class - this is a bad writing style, this should be excluded) you somewhere in the constructor create a link to the file and thus keep it open, which does not allow Add method to work with the file. And why, do we need this check in the constructor, if the library class already has OpenCreate options and so on? - Bulson
  • @Bulson You wanted to say "Design Error" instead of the word "cant", right? - AK
  • Check Exist ()? You can poke a finger that you can replace with OpenCreate - Alexey
  • @AK I said what I wanted to say. The question was with the word "cant", I answered using the terminology of the author of the question. - Bulson
  • System.IO.File.Create creates a file and returns a file stream — FileStream — until it is closed, there is no more access. - Alexander Petrov

1 answer 1

In one place of the code you are called

 System.IO.File.Create(f_Name); 

- this method creates a file, opens it and returns a FileStream file stream. While this stream is not closed - the file is busy.

In another place of the code you use

 new StreamWriter(f_name, ...); 

- an attempt to open and use the same file, apparently. Naturally, this leads to an error.

What can be done?

  1. Close the stream immediately after creating the file:

     System.IO.File.Create(f_Name).Close(); 

    The solution is working, albeit a strange one: why open the file and close it right there.

  2. Save the link to the created file stream and then use it instead of the file name:

     // Поле класса FileStream fileStream; 

    Note: this is a class field , not a local variable.

     // Сохраняем ссылку на файловый поток fileStream = System.IO.File.Create(f_Name); 

    In another place (method) of the code:

     // Используем поток вместо строкового имени файла new StreamWriter(fileStream); 

    This should work.

    Important: with this approach, be sure to implement the IDisposable interface in your class, in the Dispose method of which this file stream must be closed.

  3. Instead of System.IO.File.Create use constructor

     new FileStream(...); 

    He has as many as 15 overloads with many different parameters: FileMode , FileAccess and others. We are now interested in FileShare .

    When creating a file stream, you can specify whether we allow other processes to access it:

     new FileStream(f_Name, FileMode.Create, FileAccess.Write, FileShare.Write); 

    Here we have indicated that we are creating ( Create ) a new file, accessing it ( Write ) for reading and allowing - Share - other processes to write ( Write ) to it.

    Now in any other part of the code we can access this file using the constructor with the necessary parameters:

     using (var fs = new FileStream(f_Name, FileMode.Open, FileAccess.Write, FileShare.Write)) using (var sw = new StreamWriter(fs)) { } 

    Here we open ( Open ) a stream with write access and write permission ( Write ). Thus, the system may have several pointers to an open file, but they all must have the same access parameters.

    At the same time, it cannot be opened for reading, since initially it was not allowed. Therefore, choose the desired combination of parameters.

    Although, of course, the second method - storing the link to the open file - is more correct.