M
M
michadimin2021-12-07 20:40:46
C++ / C#
michadimin, 2021-12-07 20:40:46

How to work with files in C#?

Well, let's say...
I ask the user what file he wants to create and where. -The user enters the path to the file (including the file itself).

I create this file using File.Create()...
AND HERE IS THE BIG PROBLEM!
When I try to write to a file, they write to me that this file is being occupied by another process (as I understand it, by an I / O stream due to the fact that I used File.Create() )

Okay. Let's say you can even do WITHOUT File.Create() (just found out that File.WriteAllText() creates a file along with writing)...

But sorry. And how to delete an input/output stream? This file will hang in the PC memory without the ability to close it or what? For the method Close () I did not find something.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-12-07
@michadimin

Use using when working with files.

using(var file = File.Create(path)) {
// делаем все нужные дела через объект file
} // а тут файл автоматически закроется

This is similar to Python's with
Well, or you can manually call Close or Dispose, if in your case using is not an option.
By the way, File.WriteAllText already knows how to create a file if it does not exist

F
freeExec, 2021-12-07
@freeExec

File f = File.Create("test");
f.Write();
f.Close();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question