overwriting file with File.CreateText (C#) - c#

I am experiencing the following problem. I am using .NET Framework 1.1 and I am trying to overwrite a file using this code:
try
{
using (StringWriter writer = new StringWriter())
{
Server.Execute(path, writer);
using (StreamWriter sr = File.CreateText(filepath + fileName))
{
sr.WriteLine(writer.ToString());
}
}
}
catch (Exception exc)
{
...
}
Sometimes it works fine, but sometimes it does not overwrite the file and no exception is thrown. Could someone tell me what the issue may be or how to handle why it doesn't overwrite the file?

Why not just:
File.WriteAllText(Path.Combine(filepath, fileName), writer.ToString())
From MSDN:
Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

Could someone tell me what the issue may be or how to handle why it
doesn't overwrite the file?
Well, to answer your actual question, File.CreateText(string file) is behaving exactly as intended. if filepath + fileName to use your example, is a file that already exists, it opens the file instead of creating it. (It does not overwrite).
You could first check to see if the file exists using File.Exists(string file) then File.Delete(string file).
If File.CreateText(string file) doesn't suit your needs, you could try a different type. Maybe FileInfo?
Microsoft Says:
Creates or opens a file for writing UTF-8 encoded text.
Source: https://msdn.microsoft.com/en-us/library/system.io.file.createtext%28v=vs.110%29.aspx

over write can also be achieved with built in file.copy method.
File.copy has overload -
File.Copy Method (Source, Destination, OverWrite)
more info on msdn
hope this helps.

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

Receiving IOException

I'm getting the IOException Error when I try this, and I'm not sure what I'm doing wrong:
This is my code:
FileStream fStream = new FileStream(PDFFilePath(), FileMode.CreateNew, FileAccess.ReadWrite);
Where
private string PDFFilePath()
{
m_sFilePath = "C:/Pictures/";
return m_sFilePath;
}
What am I missing?
I'm using this FileStream to save PDF documents using the Pdf.Select NuGet. It uses a method:
PdfDocument.Save(Stream stream);
I think you should be specifying your path this way:
private string PDFFilePath(string filename)
{
m_sFilePath = #"C:\Pictures\" + filename;
return m_sFilePath;
}
Like #Reisclef said, you have to provide a file path, not a directory. Since you're using FileMode.CreateNew, it has to be a new file, so you might also want to use File.Exists(m_sFilePath) before returning.
You have several problems here.
First, if you use a path like C:\Pictures\, it'll complain about the trailing \.
Secondly, you need to specify an actual file here, not just a directory. It makes no sense to just specify a directory (rather than a file) in this case - that's why it's called a File Stream and not a Directory Stream. I suggest using Path.Combine for this. Also, if you're just trying to move an already-existing file to this directory, you should do File.Move rather than using a FileStream.
Third, you only want to use FileMode.CreateNew if there's no possibility that the file already exists in the destination folder; if it does exist, this will throw an exception.
Fourth, it's a bad practice to hardcode paths like this. You usually want to get the path from a configuration file and make sure that the Pictures directory does, in fact, exist before you try to do this operation; otherwise it may fail when you deploy it to another machine.
Fifth, the PDFFilePath method seems rather pointless in this case - you can do the same thing with a string constant or creating a readonly string in the constructor.

Creating File and copy data raising error

I am using C# in Microsoft Visual Studio 2012, I am working on the following code:
string source = "d:\\source.txt";
string newFile = "d:\\newFile.txt";
if(!File.Exists(newFile))
{
File.Create(newFile);
string content = File.ReadAllText(source);
File.AppendAllText(newFile,content);
}
This code successfully creates the File but when it compiles the File.AppendAllText(newFile,content) it generates the error:
the process cannot access the file "d:\newFile.txt" because it is being used by another process.
Why would this be?
The File.Create method returns a FileStream object. This is holding the file open for write. Until that object is closed the file cannot be written to. The best way to fix this is to simply close the returned file
File.Create(newFile).Close();
This code is essentially copying the contents of an existing file to a new one. There is already an API available that does exactly that: File.Copy. Your code could be simplified to the following
try {
File.Copy(source, newFile);
} catch (Exception) {
// File already exists or write can't occur
}
you don't need to create file , AppendAllText create if not exist, you get exception because File.Create return open file stream and then you try to access same file again. you need to properly close that stream before access the same file.
string source = "d:\\source.txt";
string newFile = "d:\\newFile.txt";
if(!File.Exists(newFile))
{
File.AppendAllText(newFile,File.ReadAllText(source););
}
File.AppendAllText:
Opens a file, appends the specified string to the file, and then
closes the file. If the file does not exist, this method creates a
file, writes the specified string to the file, then closes the file.
but you can simply do your task by one line
File.Copy(source , newFile , false);

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.

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