i want clear text file contet with this method
private void writeTextFile(string filePath, string text)
{
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
using (StreamWriter tw = new StreamWriter(filePath))
{
File.WriteAllText(filePath,"");
tw.WriteLine(text);
tw.Close();
}
}
but i get this error
The process cannot access the file because it is being used by another process.
but this not open in anywhere ,
please help me
thank's
That's because you're creating a StreamWriter, then using File.WriteAllText. Your File is already being accessed with the StreamWriter.
File.WriteAllText does just that, writes the entire string you pass to it to a file. StreamWriter is unnecessary if you're going to use File.WriterAllText.
If you don't care about overwriting an existing file, you can do this:
private void writeTextFile(string filePath, string text)
{
File.WriteAllText(filePath, text);
}
If you want to use StreamWriter (which, by the way, File.WriteAllText uses, it just hides it), and append to the file, you can do this (from this answer):
using(StreamWriter sw = File.AppendText(path))
{
tw.WriteLine(text);
}
You can use StreamWriter for creating a file for write and use Truncate to write with clearing previous content.
StreamWriter writeFile;
writeFile = new StreamWriter(new IsolatedStorageFileStream(filename, FileMode.Truncate, myIsolatedStorage));
writeFile.WriteLine("String");
writeFile.Close();
This use FileMode.Truncate
Truncate Specifies that an existing file it to be opened and then truncated so that its size is zero bytes.
Assuming that your file already exists and you want to clear its contents before populating it or whatever, I found the best way to do this with StreamWriter is..
// this line does not create test.txt file, assuming that it already exists, it will remove the contents of test.txt
Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(Path.GetFullPath(C:\test.txt), False)
// this line will now be inserted into your test.txt file
sw.Write("hey there!")
// I decided to use this solution
// this section is to clear MyFile.txt
using(StreamWriter sw = new StreamWriter(#"MyPath\MyFile.txt", false))
{
foreach(string line in listofnames)
{
sw.Write(""); // change WriteLine with Write
}
sw.Close();
}
// and this section is to copy file names to MyFile.txt
using(StreamWriter file = new StreamWriter(#"MyPath\MyFile.txt", true))
{
foreach(string line in listofnames)
{
file.WriteLine(line);
}
}
You only need to specify false in the second parameter of the constructor for StreamWriter( route, false )
String ruta = #"C:\Address\YourFile".txt";
using (StreamWriter file = new StreamWriter(ruta, false))
{
for ( int i = 0; i < settings.Length; ++i )
file.WriteLine( settings[ i ] );
file.Close();
}
The problem is with you locking the file by initializing StreamWriter onto filePath and then trying to call File.WriteAllText which also internally attempts to lock the file and eventually end up with an exception being thrown.
Also from what it looks you are trying to clear the file's content and then write something in.
Consider the following:
private void writeTextFile(string filePath, string text) {
using (StreamWriter tw = new StreamWriter(filePath, false)) //second parameter is `Append` and false means override content
tw.WriteLine(text);
}
Why not use FileStream with FileMode.Create?
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
//Do something...
}
Look at the MSDN of FileMode Enum
Create
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires 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.
Overwritten will cover/remove/clean/delete all existed file data.
if you would like to use StreamWriter, use new StreamWriter(fs).
Related
I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it:
The process cannot access the file 'myfile.ext' because it is being used by another process.
string filePath = string.Format(#"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre);
if (!File.Exists(filePath))
{
File.Create(filePath);
}
using (StreamWriter sw = File.AppendText(filePath))
{
//write my text
}
Any ideas on how to fix it?
File.Create(FilePath).Close();
File.WriteAllText(FileText);
I want to update this answer to say that this is not really the most efficient way to write all text. You should only use this code if you need something quick and dirty.
I was a young programmer when I answered this question, and back then I thought I was some kind of genius for coming up with this answer.
The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:
string filePath = #"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
//write to the file
}
The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.
When creating a text file you can use the following code:
System.IO.File.WriteAllText("c:\test.txt", "all of your content here");
Using the code from your comment. The file(stream) you created must be closed. File.Create return the filestream to the just created file.:
string filePath = "filepath here";
if (!System.IO.File.Exists(filePath))
{
System.IO.FileStream f = System.IO.File.Create(filePath);
f.Close();
}
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{
//write my text
}
FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
fs.Close();
File.Create returns a FileStream. You need to close that when you have written to the file:
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can use using for automatically closing the file.
I updated your question with the code snippet. After proper indenting, it is immediately clear what the problem is: you use File.Create() but don't close the FileStream that it returns.
Doing it that way is unnecessary, StreamWriter already allows appending to an existing file and creating a new file if it doesn't yet exist. Like this:
string filePath = string.Format(#"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre);
using (StreamWriter sw = new StreamWriter(filePath, true)) {
//write my text
}
Which uses this StreamWriter constructor.
I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.
File.Create("filename").Dispose();
This way it creates and closes the file for the next process to use it.
This question has already been answered, but here is a real world solution that
checks if the directory exists and adds a number to the end if the text file
exists. I use this for creating daily log files on a Windows service I wrote. I
hope this helps someone.
// How to create a log file with a sortable date and add numbering to it if it already exists.
public void CreateLogFile()
{
// filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
var filePath = "C:\\Logs";
// Append a backslash if one is not present at the end of the file path.
if (!filePath.EndsWith("\\"))
{
filePath += "\\";
}
// Create the path if it doesn't exist.
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
// Create the file name with a calendar sortable date on the end.
var now = DateTime.Now;
filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);
// Check if the file that is about to be created already exists. If so, append a number to the end.
if (File.Exists(filePath))
{
var counter = 1;
filePath = filePath.Replace(".txt", " (" + counter + ").txt");
while (File.Exists(filePath))
{
filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
counter++;
}
}
// Note that after the file is created, the file stream is still open. It needs to be closed
// once it is created if other methods need to access it.
using (var file = File.Create(filePath))
{
file.Close();
}
}
I think I know the reason for this exception. You might be running this code snippet in multiple threads.
you can just use using keyword around File.Create(path) to finalize the process
using(File.Create(path));
Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :
using (FileStream fs= new FileStream(#"File.txt",FileMode.Create,FileAccess.ReadWrite))
{
fs.close();
}
using (StreamWriter sw = new StreamWriter(#"File.txt"))
{
sw.WriteLine("bla bla bla");
sw.Close();
}
I try to create a text file and write some data to it. I am using the following code:
public void AddNews(string path,string News_Title,string New_Desc)
{
FileStream fs = null;
string fileloc = path + News_Title+".txt";
if (!File.Exists(fileloc))
{
using (fs = new FileStream(fileloc,FileMode.OpenOrCreate,FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fileloc))
{
sw.Write(New_Desc);
}
}
}
}
I got this exception in stream writer:
The process cannot access the file '..............\Pro\Content\News\AllNews\Par.txt'
because it is being used by another process.
Text file is created, but I can't write to it.
When you create your StreamWriter object, you're specifying the same file that you already opened as a FileStream.
Use the constructor overload of StreamWriter that accepts your FileStream object, instead of specifying the file again, like this:
using (StreamWriter sw = new StreamWriter(fs))
I would simply do this:
public void AddNews(string path, string News_Title, string New_Desc)
{
string fileloc = Path.Combine(path, News_Title+".txt");
if (!File.Exists(fileloc)) {
File.WriteAllText(fileloc, New_Desc);
}
}
Note that I use Path.Combine as a better way to create paths, and File.WriteAllText as a simple way of creating a file and writing something to it. As MSDN says:
If the target file already exists, it is overwritten.
so we first check if the file already exists, as you did. If you want to overwrite its contents, just don't check and write directly.
The issue could be that the file is open or in use. Consider checking if the file is open before writing to it...
public bool IsFileOpen(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
// Is Open
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//Not Open
return false;
}
Good Luck!
using (TextWriter tw = new StreamWriter(path, true))
{
tw.WriteLine("The next line!");
}
I want to append lines to my file. I am using a StreamWriter:
StreamWriter file2 = new StreamWriter(#"c:\file.txt");
file2.WriteLine(someString);
file2.Close();
The output of my file should be several strings below each other, but I have only one row, which is overwritten every time I run this code.
Is there some way to let the StreamWriter append to an existing file?
Use this instead:
new StreamWriter("c:\\file.txt", true);
With this overload of the StreamWriter constructor you choose if you append the file, or overwrite it.
C# 4 and above offers the following syntax, which some find more readable:
new StreamWriter("c:\\file.txt", append: true);
using (FileStream fs = new FileStream(fileName,FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(something);
}
I assume you are executing all of the above code each time you write something to the file. Each time the stream for the file is opened, its seek pointer is positioned at the beginning so all writes end up overwriting what was there before.
You can solve the problem in two ways: either with the convenient
file2 = new StreamWriter("c:/file.txt", true);
or by explicitly repositioning the stream pointer yourself:
file2 = new StreamWriter("c:/file.txt");
file2.BaseStream.Seek(0, SeekOrigin.End);
Try this:
StreamWriter file2 = new StreamWriter(#"c:\file.txt", true);
file2.WriteLine(someString);
file2.Close();
Replace this:
StreamWriter file2 = new StreamWriter("c:/file.txt");
with this:
StreamWriter file2 = new StreamWriter("c:/file.txt", true);
true indicates that it appends text.
Actually only Jon's answer (Sep 5 '11 at 9:37) with BaseStream.Seek worked for my case. Thanks Jon! I needed to append lines to a zip archived txt file.
using (FileStream zipFS = new FileStream(#"c:\Temp\SFImport\test.zip",FileMode.OpenOrCreate))
{
using (ZipArchive arch = new ZipArchive(zipFS,ZipArchiveMode.Update))
{
ZipArchiveEntry entry = arch.GetEntry("testfile.txt");
if (entry == null)
{
entry = arch.CreateEntry("testfile.txt");
}
using (StreamWriter sw = new StreamWriter(entry.Open()))
{
sw.BaseStream.Seek(0,SeekOrigin.End);
sw.WriteLine("text content");
}
}
}
Use this StreamWriter constructor with 2nd parameter - true.
Another option is using System.IO.File.AppendText
This is equivalent to the StreamWriter overloads others have given.
Also File.AppendAllText may give a slightly easier interface without having to worry about opening and closing the stream. Though you may need to then worry about putting in your own linebreaks. :)
One more simple way is using the File.AppendText it appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist and returns a System.IO.StreamWriter
using (System.IO.StreamWriter sw = System.IO.File.AppendText(logFilePath + "log.txt"))
{
sw.WriteLine("this is a log");
}
Replace this line:
StreamWriter sw = new StreamWriter("c:/file.txt");
with this code:
StreamWriter sw = File.AppendText("c:/file.txt");
and then write your line to the text file like this:
sw.WriteLine("text content");
You can use like this
using (System.IO.StreamWriter file =new System.IO.StreamWriter(FilePath,true))
{
`file.Write("SOme Text TO Write" + Environment.NewLine);
}
I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it:
The process cannot access the file 'myfile.ext' because it is being used by another process.
string filePath = string.Format(#"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre);
if (!File.Exists(filePath))
{
File.Create(filePath);
}
using (StreamWriter sw = File.AppendText(filePath))
{
//write my text
}
Any ideas on how to fix it?
File.Create(FilePath).Close();
File.WriteAllText(FileText);
I want to update this answer to say that this is not really the most efficient way to write all text. You should only use this code if you need something quick and dirty.
I was a young programmer when I answered this question, and back then I thought I was some kind of genius for coming up with this answer.
The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:
string filePath = #"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
//write to the file
}
The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.
When creating a text file you can use the following code:
System.IO.File.WriteAllText("c:\test.txt", "all of your content here");
Using the code from your comment. The file(stream) you created must be closed. File.Create return the filestream to the just created file.:
string filePath = "filepath here";
if (!System.IO.File.Exists(filePath))
{
System.IO.FileStream f = System.IO.File.Create(filePath);
f.Close();
}
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{
//write my text
}
FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
fs.Close();
File.Create returns a FileStream. You need to close that when you have written to the file:
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can use using for automatically closing the file.
I updated your question with the code snippet. After proper indenting, it is immediately clear what the problem is: you use File.Create() but don't close the FileStream that it returns.
Doing it that way is unnecessary, StreamWriter already allows appending to an existing file and creating a new file if it doesn't yet exist. Like this:
string filePath = string.Format(#"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre);
using (StreamWriter sw = new StreamWriter(filePath, true)) {
//write my text
}
Which uses this StreamWriter constructor.
I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.
File.Create("filename").Dispose();
This way it creates and closes the file for the next process to use it.
This question has already been answered, but here is a real world solution that
checks if the directory exists and adds a number to the end if the text file
exists. I use this for creating daily log files on a Windows service I wrote. I
hope this helps someone.
// How to create a log file with a sortable date and add numbering to it if it already exists.
public void CreateLogFile()
{
// filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
var filePath = "C:\\Logs";
// Append a backslash if one is not present at the end of the file path.
if (!filePath.EndsWith("\\"))
{
filePath += "\\";
}
// Create the path if it doesn't exist.
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
// Create the file name with a calendar sortable date on the end.
var now = DateTime.Now;
filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);
// Check if the file that is about to be created already exists. If so, append a number to the end.
if (File.Exists(filePath))
{
var counter = 1;
filePath = filePath.Replace(".txt", " (" + counter + ").txt");
while (File.Exists(filePath))
{
filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
counter++;
}
}
// Note that after the file is created, the file stream is still open. It needs to be closed
// once it is created if other methods need to access it.
using (var file = File.Create(filePath))
{
file.Close();
}
}
I think I know the reason for this exception. You might be running this code snippet in multiple threads.
you can just use using keyword around File.Create(path) to finalize the process
using(File.Create(path));
Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :
using (FileStream fs= new FileStream(#"File.txt",FileMode.Create,FileAccess.ReadWrite))
{
fs.close();
}
using (StreamWriter sw = new StreamWriter(#"File.txt"))
{
sw.WriteLine("bla bla bla");
sw.Close();
}
I am trying to write some text to the file using StreamWriter and getting the
path for the file from FolderDialog selected folder. My code works fine if the
file does not already exist. but if the file already exist it throws the Exception
that the file is in used by other process.
using(StreamWriter sw = new StreamWriter(FolderDialog.SelectedPath + #"\my_file.txt")
{
sw.writeLine("blablabla");
}
Now if I write like this:
using(StreamWriter sw = new StreamWriter(#"C:\some_folder\my_file.txt")
it works fine with an existing file.
It may have to do with the way you are combining your path and filename. Give this a try:
using(StreamWriter sw = new StreamWriter(
Path.Combine(FolderDialog.SelectedPath, "my_file.txt"))
{
sw.writeLine("blablabla");
}
Also, check to make sure the FolderDialog.SelectedPath value isn't blank. :)
The file is already in use, so it cannot be overwritten. However, note that this message isn't always entirely accurate - the file may in fact be in use by your own process. Check your usage patterns.
This is a cheap answer, but have you tried this workaround?
string sFileName= FolderDialog.SelectedPath + #"\my_file.txt";
using(StreamWriter sw = new StreamWriter(sFileName))
{
sw.writeLine("blablabla");
}
The other thing I would suggest is verifying that FolderDialog.SelectedPath + "\my_file.txt" is equal to the hard coded path of "C:\some_folder\my_file.txt".
Check whether the file is in fact in use by some other process.
To do that, run Process Explorer, press Ctrl+F, type the filename, and click Find.
As an aside, the best way to accomplish this task is like this:
using(StreamWriter sw = File.AppendText(Path.Combine(FolderDialog.SelectedPath, #"my_file.txt")))
EDIT: Do NOT put a slash in the second argument to Path.Combine.
Try this
using (StreamWriter sw = File.AppendText(#"C:\some_folder\my_file.txt"))
{
sw.writeLine("blablabla");
}
it will only work in existing file, so to validate if the file is new or already exists, do something like
string path = #"C:\some_folder\my_file.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
//once file was created insert the text or the columns
sw.WriteLine("blbalbala");
}
}
// if already exists just write
using (StreamWriter sw = File.AppendText(#"C:\some_folder\my_file.txt"))
{
sw.writeLine("blablabla");
}