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
Related
So I File.Create a txt and then try to write a line on it like so:
StreamWriter.WriteLine("string");
but it just skips right past it like the line doesn't exist without any messages, warnings, or errors.
This is how to use streamwriter.
using (StreamWriter writetext = new StreamWriter("C:\\sample.txt", false))
{
writetext.WriteLine("Header");
}
using (StreamWriter writetext = new StreamWriter("C:\\sample.txt", true))
{
foreach (var data in _data)
{
writetext.WriteLine("Sample");
}
}
Notice the boolean (true or false) in the second parameter of StreamWriter class
new StreamWriter("C:\\sample.txt", true)
True: Append in file if exists
False: Overwrite file if exists
this is a bit of a long answer and example. But when I am writing commands to my digital assistant this is how I use StreamWriter.
StreamWriter sw;
StreamReader sr;
then in the code you do this
Settings.Default.ShellC = #"C:\Users\" + userName + "\\Documents\\Alexis Custom Commands\\Shell Commands.txt";
scpath = Settings.Default.ShellC;
if (!File.Exists(scpath))
{ sw = File.CreateText(scpath); sw.Write("My Documents"); sw.Close(); }
the textbox is the ShellC design name. you would add that to your properties then, in your using statements add the properties. then if you wanted to read them back then you would use
StreamReader
and then ference the file as
ArrayShellCommands = File.ReadAllLines(scpath);
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.
How can I create and then modify writing on this file?
string fileName = #"C:\...\MioFile.txt";
In main:
File.CreateText(fileName);
Then when I would edit the file by adding text.
StreamWriter writer = new StreamWriter(fileName);
sw.WriteLine("Hello"+variable);
sw.Close();
But the file is empty and I cannot write anything.
I would like create a file.txt and I would like for this file to always add new information every time I call it in writing mode. A kind of "log file".
Use File.AppendAllText instead of StreamWriter. Its simple:
File.AppendAllText(filename, "Hello"+variable);
You have sw.WriteLine, But your streamwriter is called "writer". That might be the problem.
I like to use the "using" statements:
//full path
var fileName = #"C:\Users\...\Desktop\newFile2.txt";
//Get the stream in FileMode.Append (will create or open)
using (var fileStream = new FileStream(fileName,FileMode.Append))
{
//pass the fileStream into the writer.
using (var writer = new StreamWriter(fileStream))
{
writer.WriteLine("{0} => file appended", DateTime.Now);
}//dispose writer
}//dispose fileStream
Here is the code im using to write and read from text file.
StreamWriter sw1 = new StreamWriter("DataNames.txt");
sw1.WriteLine(textBox1.Text);
sw1.Close();
StreamWriter sw2 = new StreamWriter("DataNumbers.txt");
sw2.WriteLine(textBox2.Text);
sw2.Close();
FileInfo file1 = new FileInfo("DataNames.txt");
StreamReader sr1 = file1.OpenText();
while (!sr1.EndOfStream)
{
listBox1.Items.Add(sr1.ReadLine());
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
StreamReader sr2 = file2.OpenText();
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
The thing is that when I click my button to save data from my textboxes to my text files an error appears that says "The process cannot access the file 'C:\xxxx\xxxxxx\xxxxx\xxxx\xxxxx\xxxxx.txt' because it is being used by another process."
Can anyone tell me why I have this error and maybe help me fix it
Try added a using statment around your streams to make sure they are Disposed otherwise the file is still locked to the stream
Example:
//Write
using (StreamWriter sw1 = new StreamWriter("DataNames.txt"))
{
sw1.WriteLine(textBox1.Text);
}
using (StreamWriter sw2 = new StreamWriter("DataNumbers.txt"))
{
sw2.WriteLine(textBox2.Text);
}
// Read
foreach (var line in File.ReadAllLines("DataNames.txt"))
{
listBox1.Items.Add(line);
}
foreach (var line in File.ReadAllLines("DataNumbers.txt"))
{
listBox2.Items.Add(line);
}
It appears you do not close the file after you read it. After you call FileInfo.OpenText you get a StreamReader which has to be closed, either via Close method, or even better, with a using statement.
But there are already methods that do all that for you, have a look at File.WriteAllText,
File.AppendAllText and File.ReadAllLines methods.
You need to Close the StreamReader object once you do not need it any more. This should fix this issue.
I.e.
StreamReader sr1 = file1.OpenText();
try {
while (!sr1.EndOfStream)
{
listBox1.Items.Add(sr1.ReadLine());
}
}
finally {
sr1.Close();
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
StreamReader sr2 = file2.OpenText();
try {
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
}
finally {
sr2.Close();
}
You have opened files but not closed.
StreamReader sr1 = file1.OpenText();
StreamReader sr2 = file2.OpenText();
Your problem occurs, because you are not closing the stream readers.
A safer way of using external resources (the files in this case) is to embed their use in a using statement. The using statement automatically closes the resource at the end of the statement block or if the statement block if left in another way. This could be a return statement or an exception, for instance. It is guaranteed that the resource will be closed, even after an exception occurs.
You can apply the using statement on any object which implements the IDisposable interface.
// Writing to the files
using (var sw1 = new StreamWriter("DataNames.txt")) {
sw1.WriteLine(textBox1.Text);
}
using(var sw2 = new StreamWriter("DataNumbers.txt")) {
sw2.WriteLine(textBox2.Text);
}
// Reading from the files
FileInfo file1 = new FileInfo("DataNames.txt");
using (StreamReader sr1 = file1.OpenText()) {
while (!sr1.EndOfStream) {
listBox1.Items.Add(sr1.ReadLine());
}
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
using (StreamReader sr2 = file2.OpenText()) {
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
}
However, you can simplify the reading part like this
// Reading from the files
listBox1.Items.AddRange(File.ReadAllLines("DataNames.txt"));
listBox2.Items.AddRange(File.ReadAllLines("DataNumbers.txt"));
I've seen this behavior before - usually there's another process open that's blocking the file access. Do you have multiple development servers open in your taskbar? (Strange, yes, but I've seen it happen)
I would like to get the text from the textbox of my C# application into a .txt file. The issue I have is that the current saved file will overwrite the previously saved file. My current code is:
string log = #"C:\log.txt";
using (FileStream fs = new FileStream(log, FileMode.Create)) {
using (StreamWriter sw = new StreamWriter(fs)) {
foreach(string line in Textbox1.Lines)
sw.Write(line + sw.NewLine);
}
}
Is it possible to save the txt file but without it overwriting the previously saved file? Can someone help me with this.. Thanks
I belive you are talking about appending the lines:
using(FileStream fs = new FileStream(log, FileMode.Append)) {
//...
}
Try this
string log = #"C:\log"+ DateTime.Now.ToString("dd-MM-yyyy hh-mm-ss") +".txt";
Just add a time stamp to the file name
If you want to write to the same file you could use FileMode.Append:
FileStream fs = new FileStream(log, FileMode.Append)
Take care if you're in a threaded environment (ie. asp.net which I suspect since you're talking about downloads), regarding file locks and such
Try
string log = #"C:\log"+ DateTime.Now.ToString("yyyyMMddHHmmssfffffff")+".txt";
this gives precision up to ten millionths of a second
This should help:
string log = #"C:\log.txt";
int intCounter = 0;
While(File.Exists(log))
{
log = #"C:\log"+ intCounter.ToString() +".txt";
}
try this ==>
string log = #"C:\log"+ new Guid().ToString("N") +".txt";