0

After creating a file via File.Create, I want to read it afterwards with File.ReadAllText. However, I always get an exception that says that the process cannot access the file. Once the file is created, access works without problems. So I assume that the file is not yet released by File.Create at the time where it should be read. How do I solve this? Below is my method.

 public SettingsModel LoadSettings() { var _fullPath = FileHelper.GetFullPath(_fileName); if (!File.Exists(_fullPath)) { File.Create(_fullPath).Close(); } var serializedSettings = File.ReadAllText(_fullPath); var settings = JsonConvert.DeserializeObject<SettingsModel>(serializedSettings); if (settings == null) { return new SettingsModel(); } else { return settings; } } 
7
  • Try using the using clause pattern for IDisposable to be sure to free up Windows resources and handle, thus any own lock. Commented Aug 7, 2021 at 10:21
  • 1
    Does this answer your question? File being used by another process after using File.Create() and Release resources in .Net C# Commented Aug 7, 2021 at 10:23
  • @OlivierRogier Same issue with using(StreamWriter sw = new StreamWriter(_fullPath, true)) { } Commented Aug 7, 2021 at 10:34
  • 1
    Lockhunter says that the file is blocked by its own application. Commented Aug 7, 2021 at 11:06
  • 1
    I must apologize, the mistake was between the ears. In the method GetFullPath, I already check if the file exists and create it if necessary. I still thank everyone for the support. Commented Aug 7, 2021 at 11:16

1 Answer 1

0

You create an empty file to deserialize it afterwards. You can perform deserialization only if the file exists:

public SettingsModel LoadSettings() { var _fullPath = FileHelper.GetFullPath(_fileName); var settings = File.Exists(_fullPath) ? JsonConvert.DeserializeObject<SettingsModel>(File.ReadAllText(_fullPath)) : new SettingsModel(); return settings; } 
Sign up to request clarification or add additional context in comments.

6 Comments

While this is ok, the real problem is, that you can't read from a file immediatly after creation (However, I always get an exception that says that the process cannot access the file)
File.Create returns an (open) stream, so you have to close the returned Stream before reading: using (var fs = File.Create("myFile.txt")) { } var content = File.ReadAllText("myFile.txt");
File.Create(...).Close() also closes the file. I would also put that in a using block instead, but in this case, the file can't be left open. If File.Create fails, there is no stream to close.
Unfortunately, this does not solve my problem either.
I must apologize, the mistake was between the ears. In the method GetFullPath, I already check if the file exists and create it if necessary. I still thank everyone for the support.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.