Closing a File After File.Create

Closing a file after File.Create

File.Create(string) returns an instance of the FileStream class. You can call the Stream.Close() method on this object in order to close it and release resources that it's using:

var myFile = File.Create(myPath);
myFile.Close();

However, since FileStream implements IDisposable, you can take advantage of the using statement (generally the preferred way of handling a situation like this). This will ensure that the stream is closed and disposed of properly when you're done with it:

using (var myFile = File.Create(myPath))
{
// interact with myFile here, it will be disposed automatically
}

Why is File.Create needed to be closed?

File.Create is doing more than you think here. It's not just creating the file, it's also returning an active stream to the file. However, you're not doing anything with that stream. The using block in your latter example closes that stream by disposing it.

Note also that this is a significant clue about the return value:

File.Create(@"D:\MyDir\First.txt").Close();

(It actually wasn't intuitive to me when I first read your question, but looking back at it this line of code actually says it all.)

Your next step, calling File.WriteAllText also does more than you think. According to the documentation, it:

Creates a new file, writes the specified string to the file, and then closes the file.

So it would seem that your File.Create call isn't really needed here anyway.

Closing a file in C# (Unity)

Actually, if you want more control you need to use FileStream. It gives you more control while writing into files. It allows you to keep the file handle open and just write data without any additional control.

But FileStream also has some type of disadvantages.

From the documentation

When a FileStream object does not have an exclusive hold on its
handle, another thread could access the filehandle concurrently and
change the position of the operating system's file pointer that is
associated with the filehandle. In this case, the cached position in
the FileStream object and the cached data in the buffer could be
compromised. The FileStream object routinely performs checks on
methods that access the cached buffer to ensure that the operating
system's handle position is the same as the cached position used by
the FileStream object.

On the other hands :

System.IO.File contains wrappers around file operations for basic actions such as saving a file, reading a file to lines, etc. It's simply an abstraction over FileStream.

So WriteAllText is the abstraction for over the Create, Save and Close and automatically doing it and you don't need to know each of the implementations.

So the basic answer to your question is: NO, you don't need to manually close file, it will do it automatically.

When is file.close() necessary?

With the using construct you get IDisposable.Dispose called automatically at the end of the code block which will close the file. If you don't use the using statement you have to call Close yourself.

With using you also automatically get built-in try/finally exception handling which will behave more gracefully if something goes wrong before you exit your using block. That's another reason using using is a good idea instead of rolling your own.

In your case the using construct is shorthand for:

StreamWriter file2 = new System.IO.StreamWriter(myFilePath);
try
{
newFileContents.ForEach(file2.WriteLine);
}
finally
{
if (file2!= null)
((IDisposable)file2).Dispose();
}

If you decompile StreamWriter's implementation of Dispose you will see this call (among others):

this.stream.Close();

in the finally block (If you need absolute proof ;-)

How to close a file after creating it

The file is closed. It is denied for other reasons. Check the path, or maybe you could open it with FileMode File.Open(path, FileMode.Open). Otherwise check your permissions.

Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file.

Source

File being used by another process after using File.Create()

The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:

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

The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.

How to close a file after opening the file and creating a NewReader in another function?

As others have mentioned, you should return an io.ReadCloser from your function. Since the return value of bzip2.NewReader() does not satisfy io.ReadCloser, you'll need to create your own type.

type myFileType struct {
io.Reader
io.Closer
}

func OpenFile(name string) io.ReadCloser {

file, err := os.Open(name)

if err != nil {
log.Fatal(err)
}

if strings.Contains(name, ".gz") {

gzip, gerr := gzip.NewReader(file)
if gerr != nil {
log.Fatal(gerr)
}
return gzip

} else if strings.Contains(name, ".bz2") {

bzip2 := bzip2.NewReader(file)
return myFileType{bzip2, file}

} else {
return file
}
}

How do I write to the end of a file after closing it and opening it?

Use file = open("days.txt", "a") to open a file in append mode

EDIT:

Opening a file with the with keyword allows for safe and consistent closing of files, even if an Exception is thrown.

with open(myfile, 'w+'):
# Do things

# File closes automatically here

Otherwise, you have to manually call file.close(). Without that, your file will remain open, and if you are constantly opening files, you can run out of handles

Why must I Close() a file in C#?

C# doesn't have automatic deterministic cleanup. You have to be sure to call the cleanup function if you want to control when it runs. The using block is the most common way of doing this.

If you don't put in the cleanup call yourself, then cleanup will happen when the garbage collector decides the memory is needed for something else, which could be a very long time later.

using (StreamWriter outfile = new StreamWriter("../../file.txt")) {
outfile.Write(b64img);
} // everything is ok, the using block calls Dispose which closes the file

EDIT: As Harvey points out, while the cleanup will be attempted when the object gets collected, this isn't any guarantee of success. To avoid issues with circular references, the runtime makes no attempt to finalize objects in the "right" order, so the FileStream can actually already be dead by the time the StreamWriter finalizer runs and tries to flush buffered output.

If you deal in objects that need cleanup, do it explicitly, either with using (for locally-scoped usage) or by calling IDisposable.Dispose (for long-lived objects such as referents of class members).



Related Topics



Leave a reply



Submit