Error occured While writing to the file - c#

I am creating the File. At first time after creating the file, I'm immediately going to open a file but it shows error:
"The process cannot access the file 'C:\ProjectWork\Websites3\LogsArpita\ErrorLogs\Error_Log_24_4_2014.txt' because it is being used by another process."
What does it means? How can I open a file immediately for further write operation. I have tried with following code.
FileName = String.Concat("Error_Log_", DateTimeStamp + ext);
if (!File.Exists(Server.MapPath("~/LogsArpita/ErrorLogs/" + FileName)))
{
File.Create(Server.MapPath("~/LogsArpita/ErrorLogs/" + FileName));
}
//Error occured here, below line
StreamWriter tw = new StreamWriter(Server.MapPath("~/LogsArpita/ErrorLogs/" + FileName), true);
tw.WriteLine("");
tw.Write("\"" + DateTimeStampLog + "\",");
tw.Write("\"Assignments.aspx\",");
tw.Write("\"" + ErrorMessage + "\",");
tw.Write("\"" + TransactVariable + "\"");
tw.Close();

You do not need the File.Create because the StreamWriter constructor will create the file if it does not exist
This is what the msdn documentation says:
Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

Related

Having issues setting up a simple filestream

I am writing an application that allows the user to import a picture from the computer and view it in my application. The user also has an import button under the picture and he/she can select the picture's destination in the computer.
My problem is that I get following exception:
System.IO.IOException: 'The process cannot access the file 'D:\Workspaces_Foo\Foo\Theme\MyPic.png' because it is being used by another process.'
when I debug it I find the line where it's breaking. It is in:
string image = Constants.ImageName;
if (image != "NONE")
{
using (var stream = File.OpenRead(SourceDir + ImageName))
{
Directory.CreateDirectory(Path.GetDirectoryName(DestinationDir + "\\" + image));
File.Copy(SourceDir + "\\" + image, DestinationDir + "\\" + image, true); //breaks here...
}
}
I assumed that by using a filestream it would've allowed me to continue with my picture transfer. Can anyone tell me why I am getting this error?
You are opening a stream for the file. This opens the file and marks it as in use.
Then you use File.Copy to copy it, but the Operating system says the file is in use (it isn't clever enough to notice that it is in use by your own process!)
Forget the stream, try this instead.
string image = Constants.ImageName;
if (image != "NONE")
{
Directory.CreateDirectory(Path.GetDirectoryName(DestinationDir + "\\" + image));
File.Copy(SourceDir + "\\" + image, DestinationDir + "\\" + image, true);
}

How to rewrite txt file-why my code doesn't work

I want rewrite my txt file(I need delete lines). I use this code:
string cesta3 = cesta + "database.txt";
string file = new StreamReader(cesta3).ReadToEnd();
var linesToKeep = File.ReadLines(cesta3)
.Where(l => l != "Meno: " + textBox1.Text + " PN " + textBox2.Text);
But I don't know how to save my file with that same name.I try this:
File.WriteAllLines(cesta3, linesToKeep); // <== exception
var tempFile = Path.GetTempFileName();
File.Move(tempFile + ".txt", cesta3);
But it throws exception:
Additional information: Access to the path "'C:\Users\Lenovo\documents\visual studio 2015\Projects\attendancer\attendancer\bin\Debug\database.txt‌​' is denied."
How can I do ?
This line of code locks the file and prevent it from moving: string file = new StreamReader(cesta3).ReadToEnd();.
Fix:
you can properly close StreamReader after reading file text from it with using
alternatively since there is nothing in the sample using that StreamReader or result of ReadToEnd (file variable) you can simply remove that line.
Side note: File.Move will throw more exceptions after you are done with the first one as source file is unlikely to exist - I'm not sure what you were trying to do with that call.

Writting text to file c#.it's being used by another process

I am creating a text file and after that I am trying to write some text in that file.but when writing text,it's generating exception that process cannot access file because it's being used by another process. Kindly someone help :( Thanks in advance.
Here is my code
dt_Loc = loc1_ctab.GetEmpLocInfo(Session["empcd"].ToString());
string str = DateTime.Now.ToString("dd-mmm-yyyy");
str = dt_Loc.Rows[0]["loc1_abrv"].ToString() + "-" + str;
string path = FilesPath.Path_SaveFile + str + ".txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(txt_comments.Text);
tw.Close();
}
Remove the File.Create since it opens a FileStream for the file.This results in the file being open and hence you get the exception that the file is being used by another process.
if (!File.Exists(path))
{
using(StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(txt_comments.Text);
}
}
Your code giving such error because, the method Create Creates or overwrites a file in the specified path. which will return A FileStream that provides read/write access to the file specified in path. So at the time of executing the writemethod, the file is being used by the returned FS. you can use this in the following way:
using (FileStream fs = File.Create(path))
{
Byte[] info = new UTF8Encoding(true).GetBytes(txt_comments.Text);
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can Make it simple by using File.WriteAllText which will Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
string path =FilesPath.Path_SaveFile + str + ".txt";;
if (!File.Exists(path))
{
File.WriteAllText(path, txt_comments.Text);
}

File Watcher error

My file watcher event read the first file only and then I get the following error:
"Error: System.IO.IOException: The process cannot access the file 'D:\TREE\Dump\TF20141004011343313.txt' because it is being used by another process."
Here is my code:
int? msgID;
string dup ="";
try
{
//---------read from file------------
string block;
using (StreamReader sr = File.OpenText(MsgsPath + "\\" + e.Name))
{
block = sr.ReadToEnd();
}
and "using" should handle the open and close automatically, right?
I then use this code to move processed files:
File.Move(MsgsPath + "\\" + e.Name, MsgsPath + "\\Archive\\" + e.Name);
The FileSystemWatcher Created event is triggered as soon as the other process opens the file for writing. Following that, one or more Changed events will follow, when other process writes to the file, and finally closes it.
The easiest way to get around the error, would be to wait a short while before trying to access the file:
Thread.Sleep(500);
A more advanced method, is to wait a short while from the last Changed event.

The process cannot access the file when using StreamWriter

Basically I want to create a file if not existing then write message to it.
if (!File.Exists(filePath + fileName))
File.Create(filePath + fileName);
StreamWriter sr = new StreamWriter(filePath + fileName,false);
How to deal with this error?
The process cannot access the file 'c:\blahblah' because it is being used by another process.
File.Create opens a FileStream (http://msdn.microsoft.com/en-us/library/d62kzs03.aspx).
As you didn't dispose it, the file remains locked and subsequent accesses to the file will fail because of this situation if these are performed from other handles (i.e. other FileStream or the whole StreamWriter).
This code demonstrates how you should work with IDisposable objects like FileStream:
if (!File.Exists(filePath + fileName))
{
File.Create(filePath + fileName).Dispose();
using(StreamWriter sr = new StreamWriter(filePath + fileName,false))
{
}
}
Why not just use the StreamWriter constructor that takes in the file name?
StreamWriter sr = new StreamWriter(filePath + fileName);
From MSDN:
The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. If the file exists, it is overwritten; otherwise, a new file is created.
Very minor point but you could consider using Path.Combine when concatenating file names and folder paths.
Simplify your code by using single method to create and open a file:
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info = new UTF8Encoding(true)
.GetBytes("This is to test the OpenWrite method.");
fs.Write(info, 0, info.Length);
}
MSDN: (File.OpenWrite Method)
Opens an existing file or creates a new file for writing.

Categories