So i have my write to file function and it will create the file if it does not exist, and it works but the problem is first time you run the code when the file does not exist it creates it and then crash the program
//writing file to Error.txt
string path = #err;
if (!File.Exists(path)) // if does not exist make it
{
File.Create(path);
TextWriter tw = new StreamWriter(path); //crashes here after create
tw.WriteLine(i);
tw.Close();
}
Exception is:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file
'C:\Users\Desktop\TestStuff\error.txt' because it is being used by another process.
You're using 2 file streams here without closing the first one.
get rid of File.Create(path);. That method creates a file, but it also returns a file stream which you're not storing and closing.
StreamWriter will make the file for you, but it can't, because your program has a handle on it.
You could make it easier by just using
using (TextWriter tw = new StreamWriter(path, FileMode.Create, FileAccess.Write))
{
tw.WriteLine(i);
}
This would create, or reopen the file from position 0, and you can write to it like that
Related
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
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)
Here is the code I have that writes to a couple of files:
StreamWriter writer = new StreamWriter(#"C:\TotalStock\data\points\" + stockName.ToUpper() + ".txt");
for(int i = 0; i < lines; i++)
{
writer.WriteLine(lineData[i]);
postGui.Send((object state) =>
{
progressBar2.PerformStep();
}, null);
}
writer.Close();
When I delete the text files and run the code there is no issue, but then when I close the application and run it once more the program gives me the following error. What is it that causes this error and what can I do to stop it?
Error:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\TotalStock\data\points\IBM.txt' because it is being used by another process
As marc_s pointed out, the error occurs because the file you are trying to edit is opened by another application. If you are certain that you don't have the file opened in any other editor/viewer, the problem may the program itself.
If several instances of the same code run concurrently and require access to the same file, say in a multithread environement.
Does another component in your application read from the text file while you are trying to write to the file?
Does your application hang, and the second instance requires the same file?
Do you run the same tests each time?
Probably the problem is that you open the file but do not close it when you exit the program. i see you are using StreamWriter to write the data to the file.
might by you get an exception and therefor does not close the file. when playing with files you should always do:
try
{
// Your code with files
}
catch
{
}
finally
{
writer.Close();
}
other reasons might be that you are using some other File/Stream/etc. please be sure that you close all the members that need to be closed before close the program.
please share all your code if you want us to check if you forgot something else
as Sayse Is saying another way to make sure you close your writers is a using statement:
using(StreamWriter writer = new StreamWriter(#"C:\TotalStock\data\points\" + stockName.ToUpper() + ".txt");)
{
// Your code of playing with files
}
So basically I write a windows service that scans any given directory for a zip file and then uploads it to an FTP server. I added a tracing method that suppose to write into a txt file and keep a log of everything. The problems comes when I release the service into windows I get a error message in the Event Viewer( I added a LogEvent using EventLog class) that returns
System.IO.IOException: The process cannot access the file
'C:\Windows\system32\traceLog.txt' because it is being used by another
process.
The code that does the tracing is the following
private void EscribirTrace(string mensaje)
{
if (Tracing)
{
try
{
using (FileStream archivo2 = new FileStream(string.Format("{0}\\traceLog.txt", Environment.CurrentDirectory), FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
mensaje = string.Format("{0} - {1} \r\n", DateTime.Now, mensaje);
StreamWriter writer = new StreamWriter(archivo2);
writer.WriteLine(mensaje);
writer.Flush();
writer.Dispose();
}
}
catch (Exception ex)
{
LogEvent("Error en escribir tracing", ex);
}
}
}
Any ideas would be appreciated
Edit So after some research I figure that that system32 is not the best place for the file. My intention was to have that log file at the path were the service was installed. After some research I replaced the
Enviroment.CurrentDirectory
for
Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location).Replace(
Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Formated into a string.
The rest just worked pretty well.
Thank you for the responses !
Its because your using statement has not released the file yet. You have it open in the steam so you can't write to it until you close your stream.
If you want to simply write text to a file just use:
File.WriteAllText(FILEPATH, TEXTDATA);
That call will open the file, write to it, and then close it.
if it throws on the using ...make sure all other streams on the file are closed properly ...
if it throws on the streamwriter constructor
change the using to be the stream writer with the new filestream in the constructor
/Windows/system32 requires admin access. Your application probably isn't running with the proper privileges. You should try writing the log to a different (less restrictive) location. If you need to write to system32 ensure that your service is running with admin privileges.
My program is logging data to a file, at the same time a user interface displays the incoming data live. I want the logged data to be on disk within a second or two if computer/program/os/whatever shuts down. Data is coming in at least 100 times/sec.
I want the user to be able to give the log-file a new name, while logging is active. The problem is that i can't change the name of the file while it is open, even if it is by the same process.
Test case:
string fileName1 = "test.txt";
string fileName2 = "test2.txt";
using (StreamWriter sw = new StreamWriter(new FileStream(fileName1, FileMode.Create)))
{
sw.WriteLine("before");
File.Move(fileName1, fileName2); //<<-- IOException - The process cannot access the file because it is being used by another process.
w.WriteLine("after");
}
So, How do i rename a file from a process while the same process is having a stream to the file open?
You should close the first stream, rename the file, then reopen the stream:
using (StreamWriter sw = new StreamWriter(new FileStream(fileName1, FileMode.Create)))
{
sw.WriteLine("before");
sw.Close();
}
File.Move(fileName1, fileName2);
using (StreamWriter sw = new StreamWriter(new FileStream(fileName2, FileMode.Append)))
{
sw.WriteLine("after");
}
I know this answer is a bit late to help you on your porting project but perhaps it will help others!
If you open the file with the FileShare.Delete flag it will let you rename it even though it is still open :)
You can't rename a file while it is open by a process, but if you want to write to it from the other instance of your program, do this.
Try FileShare.Write. You can use it in File.Open.
using (StreamWriter sw = new StreamWriter (File.Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
{
...
}
Opening en closing the file 100 times a second will have a impact on your performance, you can log to a temp file and append the temp file every 10 seconds or so. That will give you what you want.