Creating a Txt-File and write to it [duplicate] - c#

This question already has answers here:
C# exception. File is being used by another process
(7 answers)
Closed 5 years ago.
I want to create a text file then add the text of a TextBox to it.
Creating the text file works without any problems with following code:
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
File.Create(path);
}
But I get an error that the file is being used when I try to add the text to the text file. If the file already exist before it run the code I don't get this error and the TextBox.Text is added to the File.
I use this code to add the text to the text file:
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
tw.Close();
}
}
}
Can you help me?

You don't actually have to check if the file exists, as StreamWriter will do that for you.
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
public StreamWriter(
string path,
bool append
)
Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.

You should use File.Create with using statement as it's locking the file on creating.So just change this line :
File.Create(path);
To this:
using (File.Create(path));

As you can see here, StreamWriter will actually create a file on specified path when it doesn't exist so it's useless to check for it.
I would suggest to remove the part which is creating the file and simply just start writing :
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
tw.Close();
}
}
But if you really want to create the file beforehand, remember to Dispose FileStream object created by File.Create call. Dispose call will automatically call Flush and Close for you so it's safe enough and you can do this in many ways like this :
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
using ( File.Create(path) ) ; // This will generate warnings that you're not using the object and so on, but that's okay,
}
Or like this :
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Dispose();
}

If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file. So you don't need to check if the file exists or not.
You need to make sure the file is closed before you want to modify it.

You need to Move your
tw.Close();
Outside your using. Like so :
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
tw.Close();
}
}
Edit : As pointed out, when the using ends the writer is disposed, so does not need manually closing.
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
}
}

This problem has been answered before in this thread.
Closing a file after File.Create
You will need to close the stream to the file before using it again.

Related

Streamwriter will not overwrite file, keeps appending or writes only the first line

Been looking through other people's answers and nothing seems to work.
Here is my code:
public void TaskOnClick() //getting multi-values
{
foreach (string inputJson in File.ReadLines("Assets/Text/multi-import.txt"))
{
string temperature = GetTemperatureByRegex(inputJson);
Debug.Log(temperature);
string filename = "Assets/Text/TEMP/multi-export.txt";
{
using (StreamWriter writeFile = new StreamWriter(filename, false))
{
writeFile.AutoFlush = true;
Console.SetOut(writeFile);
writeFile.WriteLineAsync(temperature.ToString());
}
}
}
}
The idea is that my parsing script gets my data and then streamwriter writes the data to a txt file. Problem is that streamwriter keeps appending the txt file instead of overwriting the file.
Whenever I try to use filestream it overwrites the file, yes, but only the first line of the data gets written, no matter what I tried.
My username speaks for itself...
What you do wrong is creating StreamWriter inside a loop. If you provide an overwrite settings it will only write 1 line.
public void TaskOnClick() //getting multi-values
{
string filename = "Assets/Text/TEMP/multi-export.txt";
using (StreamWriter writeFile = new StreamWriter(filename, false))
{
foreach (string inputJson in File.ReadLines("Assets/Text/multi-import.txt"))
{
string temperature = GetTemperatureByRegex(inputJson);
Debug.Log(temperature);
writeFile.AutoFlush = true;
Console.SetOut(writeFile);
writeFile.WriteLine(temperature.ToString());
}
}
}
But there is a shorter way of doing this with the help of LINQ.
public void TaskOnClick() //getting multi-values
{
string filename = "Assets/Text/TEMP/multi-export.txt";
var tempratures = File.ReadAllLines("Assets/Text/multi-import.txt")
.Select(GetTemperatureByRegex).ToArray();
File.WriteAllLines(filename,tempratures); // it creates a new file or overwrites
}
I have to state that above method may be dangerous if input file is too large. Because it reads entire file into memory.
Why don’t you just delete the file before opening the stream writer?
if(File.Exists(filename)){
File.Delete(filename);
}
//here whatever you need to do next

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

How to enter multiple data from textbox to txtfile without overwrite [duplicate]

This question already has answers here:
Append lines to a file using a StreamWriter
(11 answers)
Closed 7 years ago.
i need some help with entering data in a txt.file.
this is the following code:
StreamWriter file = new StreamWriter("opslag_kentekens");
string opslag_kentekens = textBox1.Text;
file.WriteLine(opslag_kentekens);
file.Close();
label20.Text = File.ReadAllText("opslag_kentekens");
So when i click on my button the text what is entered in the textBox1.text
has to go to my opslag_kentekens.txt. this works fine but when want to enter new text to my txt, it overwrites the first entered text. I want every text whats entered among each other. How do i do this? (sorry for my bad english).
file.WriteLine() will not keep your existing text.
You can use File.AppendAllText(String, String) instead:
https://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx
try this
new StreamWriter("opslag_kentekens", true);
Change your constructor to use the append overload and set it to true, that should work.
StreamWriter file = new StreamWriter("opslag_kentekens", true);
Basically you're looking at appending to a file:
From msdn:
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("This");
sw.WriteLine("is Extra");
sw.WriteLine("Text");
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
Usually, for writing (not appending), it's easier to use the File Write methods, as they are cleaner and convey your meaning better:
var some_text = "this is some text";
var out_path = #"C:\out_example.txt";
System.IO.File.WriteAllLines(out_path, some_text);
Even better and cleaner, look #Liem's answer, which is the same but with the correct Append syntax.

System IO Exception : the process cannot access the file because it is being used by another process c#

I have seen several post for this problem .I have implemented all suggestion like using flush() , close() method on streamwriter and connection Object,use GC.Collect() to force cleanup,, use using{} to autodispose
I am Doing Simple Get Operation from DB and write to text file ..here is my Code
public void WriteToFile(string ProductName)
{
//Already Got Data from DB and stored in "ProductName"
//saving in File
if (!File.Exists(path11))
{
File.Create(path11);
StreamWriter tw = new StreamWriter(path11);
tw.WriteLine(ProductName+"#"+DateTime.Now.ToString());
tw.Flush();
tw.Close();
}
else if (File.Exists(path11))
{
StreamWriter tw = new StreamWriter(path11, true);
tw.WriteLine(ProductName + "#" + DateTime.Now.ToString());
tw.Flush();
tw.Close();
}
GC.Collect();
}
Another suggestion I Got is to lock the object ..But I cannot implement it ..
Any suggestion would be Helpful
File.Create creates the file and returns an open stream. You don't really need all that logic. Just use new StreamWriter(path11, true) which will create the file if it doesn't exist and append to it if it does. Also using is helpful:
public void WriteToFile(string ProductName)
{
//Get Data from DB and stored in "ProductName"
using (var tw = new StreamWriter(path11, true))
{
tw.WriteLine(ProductName+"#"+DateTime.Now.ToString());
}
}
FileCreate returns a stream which you should use to instantiate StreamWriter:
var file = File.Create(path11);
StreamWriter tw = new StreamWriter(file);
And you should use using blocks to make sure your stream and file is closed when you're finished writing.

"File in use" error when writing to text file

I'm getting the error The process cannot access the file 'C:\Users\Ryan\Desktop\New folder\POSData.txt' because it is being used by another process. when I try to create a file and then write to it. What process is using the file?? I checked for a file.close to call after I create the file, but it doesn't exist. How do I get past this? Thanks!
Heres my code:
MessageBox.Show("Please select a folder to save your database to.");
this.folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.Desktop;
DialogResult result = this.folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
databasePath = folderBrowserDialog1.SelectedPath;
if (!File.Exists(databasePath + "\\POSData.txt"))
{
File.Create(databasePath + "\\POSData.txt");
}
using (StreamWriter w = new StreamWriter(databasePath + "\\POSData.txt", false))
{
w.WriteLine(stockCount);
}
}
Edit: Only happens when creating the file. If it already exists, no error occurs.
Actually, don't even bother using File.Create. The reason you're getting that error is because File.Create is opening up a stream on that text file.
string filePath = "databasePath + "\\POSData.txt"";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
//write to the file
}
You are keeping the file open when you call File.Create (i.e. you never close the file).
StreamWriter will create the file for you if it doesn't exist, so I wouldn't bother checking yourself. You could just remove the code that checks whether it exists and creates it if it doesn't.
if (result == DialogResult.OK)
{
databasePath = folderBrowserDialog1.SelectedPath;
using (StreamWriter w = new StreamWriter(databasePath + "\\POSData.txt", false))
{
w.WriteLine(stockCount);
}
}
Note that if the file doesn't exist, the second bool parameter in the StreamWriter constructor is ignored.
File.Create also opens the file for reading/writing. As such, you're leaving an open FileStream when you File.Create.
Assuming that overwriting is OK, then you probably want to do something like this:
using (var fs = File.Create(databasePath + "\\POSData.txt"))
using (StreamWriter w = new StreamWriter(fs))
{
w.WriteLine(stockCount);
}
given that File.Create:
Creates or overwrites a file in the specified path.
The File.Create returns a FileStream object that might need to be closed.
The FileStream object created by this method has a default FileShare
value of None; no other process or code can access the created file
until the original file handle is closed.
using (FileStream fs = File.Create(databasePath + "\\POSData.txt"))
{
fs.Write(uniEncoding.GetBytes(stockCount), 0, uniEncoding.GetByteCount(stockCount));
}
I used this and it worked
`File.AppendAllText(fileName,"");`
This creates a new file, writes nothing to it, then closes it for you.

Categories