Подтвердить что ты не робот

Файл, используемый другим процессом после использования File.Create()

Я пытаюсь определить, существует ли файл во время выполнения, если нет, создайте его. Однако я получаю эту ошибку, когда пытаюсь ее написать:

Процесс не может получить доступ к файлу 'myfile.ext', потому что он используется другим процессом.

string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
if (!File.Exists(filePath)) 
{ 
    File.Create(filePath); 
} 

using (StreamWriter sw = File.AppendText(filePath)) 
{ 
    //write my text 
}

Любые идеи о том, как его исправить?

4b9b3361

Ответ 1

Метод File.Create создает файл и открывает файл FileStream в файле. Таким образом, ваш файл уже открыт. Вам действительно не нужен файл. Создайте метод вообще:

string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
    //write to the file
}

Логическое значение в конструкторе StreamWriter приведет к добавлению содержимого, если файл существует.

Ответ 2

    File.Create(FilePath).Close();
    File.WriteAllText(FileText);

Ответ 3

При создании текстового файла вы можете использовать следующий код:

System.IO.File.WriteAllText("c:\test.txt", "all of your content here");

Использование кода из вашего комментария. Созданный файл (поток) должен быть закрыт. File.Create возвращает поток потока в только что созданный файл.:

string filePath = "filepath here";
if (!System.IO.File.Exists(filePath))
{
    System.IO.FileStream f = System.IO.File.Create(filePath);
    f.Close();
}
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{ 
    //write my text 
}

Ответ 4

FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
fs.Close();

Ответ 5

File.Create возвращает FileStream. Вам нужно закрыть это, когда вы записали файл:

using (FileStream fs = File.Create(path, 1024)) 
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

Вы можете использовать его для автоматического закрытия файла.

Ответ 6

Я обновил ваш вопрос с помощью фрагмента кода. После правильного отступов сразу становится ясно, в чем проблема: вы используете File.Create(), но не закрываете FileStream, который он возвращает.

Делать это не нужно, StreamWriter уже позволяет добавлять существующий файл и создавать новый файл, если он еще не существует. Вот так:

  string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
  using (StreamWriter sw = new StreamWriter(filePath, true)) {
    //write my text 
  }

Использует этот конструктор StreamWriter.

Ответ 7

Этот вопрос уже был дан ответ, но вот реальное мировое решение, которое проверяет, существует ли каталог и добавляет номер в конец, если текстовый файл существует. Я использую это для создания ежедневных файлов журнала в службе Windows, которую я написал. я надеюсь, это поможет кому-то.

// How to create a log file with a sortable date and add numbering to it if it already exists.
public void CreateLogFile()
{
    // filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
    var filePath = "C:\\Logs";

    // Append a backslash if one is not present at the end of the file path.
    if (!filePath.EndsWith("\\"))
    {
        filePath += "\\";
    }

    // Create the path if it doesn't exist.
    if (!Directory.Exists(filePath))
    {
        Directory.CreateDirectory(filePath);
    }

    // Create the file name with a calendar sortable date on the end.
    var now = DateTime.Now;
    filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);

    // Check if the file that is about to be created already exists. If so, append a number to the end.
    if (File.Exists(filePath))
    {
        var counter = 1;
        filePath = filePath.Replace(".txt", " (" + counter + ").txt");
        while (File.Exists(filePath))
        {
            filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
            counter++;
        }
    }

    // Note that after the file is created, the file stream is still open. It needs to be closed
    // once it is created if other methods need to access it.
    using (var file = File.Create(filePath))
    {
        file.Close();
    }
}

Ответ 8

Попробуйте это: он работает в любом случае, если файл не существует, он создаст его, а затем напишет на него. И если он уже существует, нет проблем, он откроется и напишет ему:

using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
{ 
     fs.close();
}
using (StreamWriter sw = new StreamWriter(@"File.txt")) 
 { 
    sw.WriteLine("bla bla bla"); 
    sw.Close(); 
 }