BinaryWriter to overwrite an existing file c# - 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)

Related

DirectoryNotFoundException even when file does exist

This is the code:
string file = Path.Combine(Environment.CurrentDirectory, "test.txt");
if (!File.Exists(file)) {
File.CreateText(file); // will throw always
}
using (var writer = new StreamWriter(file)) { // will throw always
//...
}
This will throw a DirectoryNotFoundException if the file doesn't exist and if it attempts to create it, and if the file does exist, then it will throw DirectoryNotFoundException when trying to use StreamWriter. I don't believe this code is wrong, so I am at a loss at what is the problem.
Update
The value of file is /tmp/test.txt. Yes, it always is throwing, the exception is
System.IO.DirectoryNotFoundException: Could not find a
part of the path '/tmp/test.txt'
Update
A reboot has fixed this. I have no idea why this was being caused, but it might've simply been an IDE issue.
You are opening a file with
File.CreateText(file);
File.CreateText(String) Method
Returns StreamWriter A StreamWriter that writes to the specified file
using UTF-8 encoding.
Then you are not closing it. Then you are trying to access the open file by opening it again
using (var writer = new StreamWriter(file))
However, the exception you are getting is another problem again. When using StreamWriter
DirectoryNotFoundException The specified path is invalid (for example,
it is on an unmapped drive).
All the above aside, what i suggest you do is
string file = Path.Combine(Environment.CurrentDirectory, "test.txt");
Console.WriteLine(file);
//FileMode.Create will create or overwwrite the file
using (var fs = new FileStream(file,FileMode.Create))
using (var writer = new StreamWriter(fs))
{
}
Then if you still have problems, go to that directory and check if the file is there, check the permissions on the directory and file and make sure you have the appropriate access.
In short your code is suspect and you need to fix it, secondly you need to be sure what file it is your opening, thirdly, you need to check the permissions for that file and or directory

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.

File is used by another process: How to solve this Error?

I am trying to open a file, but I received:
The process cannot access the file because it is being used by another process. The File is an XML-Document. Can anyone help?
string activeDirectory = #"X:\SubGraph\";
string[] files = Directory.GetFiles(activeDirectory);
foreach (string fileName in files){
FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
After using a file, you must to close it, I think:
foreach (string fileName in files)
{
FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
//your code
file.Close();
}
If you are using this piece of code in some kind of loop you need to close your FileStream each time before finishing loop cycle.
file.Close();
Or use "using" construction like this:
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
// your code goes here
file.Close();
}
Moreover, you better to accustom yourself to close all manually created streams after they are unnecessary anymore.
Under some circumstances Windows locks the files. In your case can be:
Another process is locking the file. It might be windows or you av software or who knows.
In order to discover who is locking the file you might several tools like wholockme or Unlocker. These tools will tell you which process is locking the file and even allow you to unlock it.
Maybe you are locking your own file. In your code snippet seems you are not closing the file you are reading (Maybe you can edit your question and add all code). You should remember to include:
file.Close();
... or file will remain open.

File.OpenWrite appends instead of wiping contents?

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.

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