Creating File and copy data raising error - c#

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);

Related

Created ZIP archive is invalid

I'm using ZipFile.Open() to create an archive, then adding entries using CreateEntryFromFile(). The resulting file is invalid according to Windows. 7-zip can open the file, but only part of the files are listed.
The code looks like this:
using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create))
{
while (reader.Read())
{
object myValue = reader.GetValue(0);
string objectId = myValue.ToString();
string objectPath = Path.Combine(myPath, objectId);
string[] files = Directory.GetFiles(objectPath);
if (files.Length > 0)
{
archive.CreateEntryFromFile(files[0], Path.GetFileName(files[0]));
}
}
}
As you can see, I do dispose of the ZipArchive when I'm done, and unlike every other question about this problem, I don't use any streams, so there's nothing to flush.
Anyone know what's wrong?
It could be possible that the file being added to the archive is being used by another process and cannot be accessed. To avoid this, you can try wrapping the CreateEntryFromFile method in a try-catch block and handle the IOException that could be thrown if the file is in use. You can also try closing any streams or file handles that may have been opened on the file before adding it to the archive.

copy the data from xml file and paste in same file and overwrite using FIle.Copy()

I am trying to copy data of one file and pasting it into the same file which means overwriting it. I learn that overwrite the file data using file.copy() cannot be possible. but from the one of the post says that if I use File.Copy(Source file, destination file, true) than overwrite is possible. I tried to use but it didn't work. if anyone have solution for that than it will be big help.
public void EditRole(string oldRole, string newRole)
{
if (File.Exists(roleXMLLoc))
{
XDocument doc = XDocument.Load(roleXMLLoc);
var edit = doc.Element("Roles").Elements("Role").Where(x => x.Value == oldRole).SingleOrDefault();
edit.Value = newRole;
doc.Save(roleXMLLoc);
if (File.Exists(userPermissionLoc))
{
File.Copy(userPermissionLoc, userPermissionLoc, true); SaveData();
}
}
}
To read or write files you should open a Stream (https://learn.microsoft.com/en-us/dotnet/standard/io/). If you need to read and write in the same time, then you should use 2 separate streams for reading and writing into 2 separate files. Operating system will protect file from being opened by 2nd stream, otherwise you would fall into problems of concurrency: you read the inactual data that is already being changed by writing stream.
The logic can be:
Read file and close Reading stream. Then open file for writing and do what you need.
OR
Open Reading stream for fileToRead.xml and open Writing stream for temporary fileToWrite.xml. After you done, you can close both streams, remove the source file and rename the new file.

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.

overwriting file with File.CreateText (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.

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