File.OpenWrite appends instead of wiping contents? - c#

I was using the following to write to a file:
using(Stream FileStream = File.OpenWrite(FileName))
FileStream.Write(Contents, 0, Contents.Length);
I noticed that it was simply writing to file file correctly, but didn't wipe the contents of the file first. I then decided to simply use:
File.WriteAllBytes(FileName, Contents);
This worked fine.
However, why doesn't File.OpenWrite automatically delete the contents of the file as the other languages i've used do for their OpenWrite style function, and have a instead of appending?
Is there any method to do this?

This is the specified behavior for File.OpenWrite:
If the file exists, it is opened for writing at the beginning. The existing file is not truncated.
To do what you're after, just do:
using(Stream fileStream = File.Open(FileName, FileMode.Create))
fileStream.Write(Contents, 0, Contents.Length);
Your current call is equivalent to use FileMode.OpenOrCreate, which does not cause truncation of an existing file.
The FileMode.Create option will cause the File method to create a new file if it does not exist, or use FileMode.Truncate if it does, giving you the desired behavior. Alternatively, you can use File.Create to do this directly.

Yes you are right. File.OpenWrite does not overwrite the file.
The File.Create is used to overwrite the file if exists.

Related

System.IO.File.OpenRead is working but System.IO.FileStream is not working?

In my application i am reading .PDF file useing System.IO.FileStream (filePath). This is working fine when folder have local user right. When i remove Local user right from folder that time this gives access denied error.
I am use this code...
System.IO.FileStream objFStream = new System.IO.FileStream(strPath, System.IO.FileMode.Open);
byte[] bytRead = new byte[(int)objFStream.Length];
objFStream.Read(bytRead, 0, (int)objFStream.Length);
objFStream.Close();
objFStream.Dispose();
Once i replace System.IO.FileStream to System.IO.File.OpenRead(strPath) it will work.
Replace code is...
System.IO.FileStream objFStream = System.IO.File.OpenRead(strPath);
byte[] bytRead = new byte[(int)objFStream.Length];
objFStream.Read(bytRead, 0, (int)objFStream.Length);
objFStream.Close();
objFStream.Dispose();
I want to know what is the different between this?
If any one know please help.
File.OpenRead method uses FileAccess.Read while opening the file.It's the difference:
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
The documentation says about the constructor you are using:
For constructors without a FileAccess parameter, if the mode parameter is set to Append, Write is the default access. Otherwise, the access is set to ReadWrite.
So I guess you don't have permission to write the file. That's why it throws exception.You can verify this by trying opening the stream with ReadWrite access:
new FileStream(strPath, FileMode.Open, FileAccess.ReadWrite);
... new System.IO.FileStream(strPath, System.IO.FileMode.Open)
When you only say "I want to open the file" then .NET doesn't know if you are going to read or write the file. So it guesses at both to be on the safe side, FileAccess.ReadWrite. However, file system directories very commonly only allow a user to read files and forbid writing. Standard examples on any machine are the c:\windows and c:\program files directories and their sub-directories. So the exception is nothing unexpected.
You have to be explicit about your intention with the file. Like File.OpenRead() is implicitly by just its name. You must add the FileAccess.Read argument.
Anecdotal: the File class was added to the framework very late. Inspired by Microsoft conducting usability studies on the framework. They asked experienced programmers whom otherwise never had seen .NET to use FileStream to write a sample program. Nobody got it right.

BinaryWriter to overwrite an existing file c#

To write a picture on the memory of my pocket pc i use the following code:
pic = (byte[])myPicutureFromDatabase;
using (var fs = new BinaryWriter(new FileStream(filepath, FileMode.Append, FileAccess.Write)))
{
fs.Write(pic);
fs.Flush();
continue;
}
I wanted to ask you if this method overwrite the file with new values if the file with this name already exist or do nothing because already exist this file?
I need to overwrite the file in eventuality that this file already exist but with old value.
From MSDN FileMode.Create
Specifies that the operating system should create a new file. If the
file already exists, it will be overwritten. This requires
FileIOPermissionAccess.Write permission. FileMode.Create is equivalent
to requesting that if the file does not exist, use CreateNew;
otherwise, use Truncate. If the file already exists but is a hidden
file, an UnauthorizedAccessException exception is thrown.
Where as FileMode.Append
Opens the file if it exists and seeks to the end of the file, or
creates a new file. This requires FileIOPermissionAccess.Append
permission. FileMode.Append can be used only in conjunction with
FileAccess.Write. Trying to seek to a position before the end of the
file throws an IOException exception, and any attempt to read fails
and throws a NotSupportedException exception.
So, you should use this
pic = (byte[])myPicutureFromDatabase;
using (var fs = new BinaryWriter(new FileStream(filepath, FileMode.Create, FileAccess.Write)))
{
fs.Write(pic);
fs.Flush();
continue;
}
No it appends the lines, you have specified it by writing FileMode.Append, you should specify FileMode.Create in order to append lines (or create a new file if it not exists)

c# overwriting/saving current file

I am doing editor in c#, windows forms. I wish to save 'new content' of file in the same file (usual usage of 'save' option) but I receive IOException, [ the process cannot access the file ' filename' because it is being used by another process.
I have method that writes to a NEW file and it works. How to use it to overwrite current file.
Edit:
I am using binarywriter http://msdn.microsoft.com/en-us/library/atxb4f07.aspx
Chances are that when you loaded the file, you didn't close the FileStream or whatever you used to read it. Always use a using statement for your streams (and other types implementing IDisposable), and it shouldn't be a problem. (Of course if you actually have that file open in a separate application, that's a different problem entirely.)
So instead of:
// Bad code
StreamReader reader = File.OpenText("foo.txt");
string data = reader.ReadToEnd();
// Nothing is closing the reader here! It'll keep an open
// file handle until it happens to be finalized
You should use something more like:
string data;
using (TextReader reader = File.OpenText("foo.txt"))
{
data = reader.ReadToEnd();
}
// Use data here - the handle will have been closed for you
Or ideally, use the methods in File which do it all for you:
string text = File.ReadAllText("foo.txt");
Check if you're closing stream to the file. If not then you're blocking yourself.
Assuming that you have correctly closed the stream you used to open and read the file initially, to create, append or fail depending of file existence you should use the FileMode parameter in FileStream constructor.
Everything depends on the way you open the FileStream, see here: FileStream Constructor (String, FileMode)
if you specify FileMode Create:
Specifies that the operating system should create a new file. If the
file already exists, it will be overwritten. This requires
FileIOPermissionAccess.Write. System.IO.FileMode.Create is equivalent
to requesting that if the file does not exist, use CreateNew;
otherwise, use Truncate. If the file already exists but is a hidden
file, an UnauthorizedAccessException is thrown.

How to avoid from The process cannot access the file XXX.XXX because it is being used by another process

I transfer file from computer to computer Through a WebService.
After the file was transfer I need to read its size.
When I try to read the file size I get:
The process cannot access the file XXX.XXX because it is being used by another process
What can I do to avoid this error?
i read the file like this:
LocalFileSize = File.Open(TermSendName, FileMode.Open, FileAccess.Read).Length.ToString();
how to close this ?
I guess that you are using a FileStream to read the file.
Close the stream when the transfer has completed.
Try this
FileStream stream = File.Open(TermSendName, FileMode.Open, FileAccess.Read);
LocalFileSize = stream.Length.ToString();
stream.Close();
If you only want to get length of file you can also do something like
FileInfo fileInfo = new FileInfo(fileName);
string size = fileInfo.Length.ToString();
Please check the following Stack Overflow link, I faced the same issue and got fixed here:
The process cannot access the file because it is being used by another process.c#

Write string to text file and ensure it always overwrites the existing content.

I have a string with a C# program that I want to write to a file and always overwrite the existing content. If the file isn't there, the program should create a new file instead of throwing an exception.
System.IO.File.WriteAllText (#"D:\path.txt", contents);
If the file exists, this overwrites it.
If the file does not exist, this creates it.
Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.
Use the File.WriteAllText method. It creates the file if it doesn't exist and overwrites it if it exists.
Generally, FileMode.Create is what you're looking for.
Use the file mode enum to change the File.Open behavior. This works for binary content as well as text.
Since FileMode.Open and FileMode.OpenOrCreate load the existing content to the file stream, if you want to replace the file completely you need to first clear the existing content, if any, before writing to the stream. FileMode.Truncate performs this step automatically
// OriginalFile:
oooooooooooooooooooooooooooooo
// NewFile:
----------------
// Write to file stream with FileMode.Open:
----------------oooooooooooooo
var exists = File.Exists(path);
var fileMode = exists
? FileMode.Truncate // overwrites all of the content of an existing file
: FileMode.CreateNew // creates a new file
using (var destinationStream = File.Open(path, fileMode)
{
await newContentStream.CopyToAsync(destinationStream);
}
FileMode Enum
If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?
I'm assuming your using a streams here, there are other ways to write a file.

Categories

Resources