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

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.

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

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

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.

How to write at the next line in the next opening of the csv file?

At first run, my program, writes to a csv file in the first line,
But, when I'm running my program at the second.. third.. time, it runs over the first line..
how can i correct it?
I would like to have a CSV file input of all the entering to my program.
The code is as follows:
private void WriteToCsvFile()
{
var us = users.ElementAt(0);
string names = "Number',";
string userAnswer = (us.userName + ",");
foreach (string ss in user)
{
string str = Path.GetFileName(ss);
names = names + str + ",";
}
foreach (string ans in us.answer)
{
userAnswer = userAnswer + ans + ",";
}
using (StreamWriter sw = new StreamWriter("EntranceLog.csv"))
{
sw.WriteLine(names);
sw.WriteLine(userAnswer);
}
this.Close();
}
Add true parameter in the constructor:
using (StreamWriter sw = new StreamWriter("EntranceLog.csv", true))
The second parameter named append controls whether an existing file shall be overwritten or appended. MSDN states:
true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.
Each time it is run, you are creating a new file with the same name is overwriting the older file. That is the default behavior of the specific constructor you are using.
You want to use this constructor instead and specify the append parameters as true:
using (StreamWriter sw = new StreamWriter("EntranceLog.csv", true))
{
// write your file as normal
}

StreamWriter is not able to write in file

My code is
System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File);
objStreamWriter.Write(txtEditor.Text);
objStreamWriter.Close();
txtEditor.Text = string.Empty;
I got a message The file has been modified out side of............. but my text file is empty. When in debug mode, I got a value of textEditor and path is not a problem. Am I missing some stupid things.
Thanks.
You have to verify the content of txtEditor before you write it to disk file.
string text=txtEditor.Text;
if(text.Trim.Length!=0)
{
using(System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File))
{
objStreamWriter.Write(text);
}
}
Use the StreamWriter by the "using" keyword for correct writing in to textfile.
using (StreamWriter writer = new StreamWriter("important.txt"))
{
writer.Write("Word ");
writer.WriteLine("word 2");
writer.WriteLine("Line");
}
Refer to the C# Using StreamWriter for more info

Writing a Text File in memory and saving it with savefiledialog

I am trying to make a text file in memory, add some lines to it and at the end save the file in a text file. I can handle the savedialog part but I dont know how to get the text file from memory. Any help and tips will be appriciated.
What I am doing so far is:
//Initialize in memory text writer
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);
please note
I will call tw.WriteLine() add more lines in different places so I want to save this at end of program (so this shouldent be wrapped between something like using{} )
UPDATE
StringBuilder seems to be a more reliable option for doing this! I get strange cut-outs in my text file when I do it using MemoryStream.
Thanks.
I think your best option here would be to write to a StringBuilder, and when done, File.WriteAllText. If the contents are large, you might consider writing directly to the file in the first place (via File.CreateText(path)), but for small-to-medium files this should be fine.
var sb = new StringBuilder();
sb.AppendLine("HELLO WORLD!");
sb.AppendLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");
File.WriteAllText(path, sb.ToString());
Or, something nigh-on the same as #Marc's answer, but different enough that I think it's worth putting out there as a valid solution:
using (var writer = new StringWriter())
{
writer.WriteLine("HELLO WORLD!");
writer.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");
File.WriteAllLines(path, writer.GetStringBuilder().ToString());
}
Where path is a string representing a valid file system entry path, predefined by you somewhere in the application.
Assume your SaveFileDialog name is "dialog"
File.WriteAllBytes(dialog.FileName, Encoding.UTF8.GetBytes("Your string"));
or
var text = "Your string";
text += "some other text";
File.WriteAllText(dialog.FileName, text);
also in your own solution you can do this :
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);
// just add this
File.WriteAllBytes(dialog.FileName, ms.GetBuffer());
Something like this.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
using (FileStream file = File.CreateText(dlg.FileName)
{
ms.WriteTo(file)
}
}
I haven't worried about whether the file already exists but this should get you close.
You might need a ms.Seek(SeekOrgin.Begin, 0) too.
Another way of appending text to the end of a file could be:
if (saveFileDialog.ShowDialog() == DialogResult.OK) {
using (var writer = new StreamWriter(saveFileDialog.Filename, true)) {
writer.WriteLine(text);
}
}
supposing that text is the string you need to save into your file.
If you want to append new lines to that string in an easy way, you can do:
var sb = new StringBuilder();
sb.AppendLine("Line 1");
sb.AppendLine("Line 2");
and the resulting string will be sb.ToString()
If you already have a Stream object (in your example, a MemoryStream), you can do the same but replace the line:
using (var writer = new StreamWriter(saveFileDialog.Filename, true)) {
by
using (var writer = new StreamWriter(memoryStream)) {
Edit:
About wrapping the statements inside using:
Take in count that this is not a problem at all. In my first example, all you will have to do is to keep that StringBuilder object, and keep adding lines to it. Once you have what you want, just write the data into a text file.
If you are planning to write more than once to the text file, just clear the StringBuilder everytime you write, in order to not get duplicated data.

Categories