1

Всем добрый вечер. Когда файл уже создан, всё хорошо. Но если программа сначала создаёт его, вылезает ошибка, что файл используется. Но почему? Процесс тут один, к записи в поток программа переходит после того, как файл создаст.

Вот сама ошибка: "The process cannot access the file 'C:\Users\Tpoc3\Source\Repos\Bachelor-s-Project\TextEditorServer\bin\Debug\files\dd.txt' because it is being used by another process."

public void CreateFile(string fileName, string data)
        {
            DirectoryInfo currentDirectory = new DirectoryInfo(filePath);
            if (!currentDirectory.Exists) currentDirectory.Create();
            filePath += @"\" + fileName;
            if (!File.Exists(filePath)) File.Create(filePath);

            using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8))
            {
                sw.WriteLine(data);
            }
        }

1 ответ 1

1

Ресурс (FileStream), который возвращается вызовом File.Create, должен быть освобожден:

if (!File.Exists(filePath)) 
  using (File.Create(filePath)) { }

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.