Hello I have this line of code to write every line of richTextBox into my .txt file but at the final the txt file is empty but when debug it reads every line. May I know how this code should be improved to do what I want?
string Path = (#"C:\Users\x\Documents\Visual Studio 2012\Projects\MTest\txtCmdLog.txt");
StreamWriter sw = new StreamWriter(File.Open(Path, System.IO.FileMode.Append));
for (int i = 0; i <= txtCmdLog.Lines.Length; i++)
{
sw.WriteLine(txtCmdLog.Lines[i] + "\n");
}
sw.Close();
Thank you for your time.
Change your loop to:
for (int i = 0; i < txtCmdLog.Lines.Length; i++)
{
sw.WriteLine(txtCmdLog.Lines[i]);
}
Don't use <= in the loop's condition check. You also don't need to append a newline character in the call to WriteLine, since that method already writes a newline.
Points to remember:
1.you need to loop through 0 to lines.Length-1.so remove = in <= condition.
2.for disposing the StreamWriter object use using{} block so that you don't need to call close().
Diposal of StreamWriter object will be taken care by using {} block
string Path = (#"C:\Users\x\Documents\Visual Studio 2012\Projects\MTest\txtCmdLog.txt");
using(StreamWriter sw = new StreamWriter(File.Open(Path, System.IO.FileMode.Append)))
{
for (int i = 0; i < txtCmdLog.Lines.Length; i++)
{
sw.WriteLine(txtCmdLog.Lines[i] + "\n");
}
}
The easy way to do this is:
File.WriteAllLines(filename, arrayOfStrings);
Related
I have a piece of code that is adding lines of text to a System.IO.StringWriter.
When it gets above a certain size, I want to purge lines from the beginning.
How do I do that? Can it be done?
System.IO.StringWriter log = new System.IO.StringWriter();
log.WriteLine("some text");
log.WriteLine("more text");
// some how remove the first line ????
A possible solution to your problem involves the use of the Queue class. You can add your text to this object and when it reaches a certain size you start trimming away the initial data
For example
void Main()
{
int maxQueueSize = 50;
var lines = File.ReadAllLines(filePath);
Queue<string> q = new Queue<string>(lines);
// Here you should check for files bigger than your limit
....
// Trying to add too many elements
for (int x = 0; x < maxQueueSize * 2; x++)
{
// Remove the first if too many elements
if(q.Count == maxQueueSize)
q.Dequeue();
// as an example, add the x converted to string
q.Enqueue(x.ToString());
}
// Back to disk
File.WriteAllLines(filePath, q.ToList());
}
System.IO.StringWriter log = new System.IO.StringWriter();
log.WriteLine("some text");
log.WriteLine("more text");
// some how remove the first line ????
var sb = log.GetStringBuilder(); //get the underlying StringBuilder
var newLinePosition = sb.ToString().IndexOf(Environment.NewLine); //find the first newline
sb.Remove(0, newLinePosition + Environment.NewLine.Length); //remove from start to the newline... including the newline itself
You can, instead of writing to a stream write to a different data structure (such as a list) and use an iterator to loop over your lines and replace them if you hit a certain threshold.
List<string> log = new List<string>();
int idx = 0;
//...
if (idx > 10) // your max amount of messages
{
idx = 0;
}
if (log.Count < idx)
{
log.Add("more Text");
}
else
{
log[idx] = "more Text";
}
of course you should wrap this in a class for logging.
I am currently working on an assignment for school where I am trying to write a 2D string array into a text file. I have the array and know its working fine however every time I try to read the file into Streamwriter I get "System.ArgumentException: 'Illegal characters in path.'". I am relatively new to C# and I have no idea how to fix this.
This is my code. I just need to know how to write my 2D array into the text file without getting this error. Thanks, all and any help is much appreciated!
// This line under is where the error happens
using (var sw = new StreamWriter(Harvey_Norman.Properties.Resources.InventoryList))
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
sw.Write(InventoryArray[i, j] + " ");
}
sw.Write("\n");
}
sw.Flush();
sw.Close();
}
My guess is that Harvey_Norman.Properties.Resources.InventoryList is a resource in your project that is typed as a string-- and the value of that string is not a valid path for your operating system.
StreamWriter will either take a string, in which case it expects to open a file with the path of that string; or it will take a stream, and you can write to that stream. It looks like you are trying to do the former; but you need to check the value of that resource to see if it is a vaild path.
You're trying to construct a StreamWriter with an invalid file path.
Also, if you're just writing text out, you can use File.CreateText() to create a StreamWriter, for example:
var tempFilePath = Path.GetTempFileName();
using (var writer = File.CreateText(tempFilePath))
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
if (j > 0)
writer.WriteLine(" ");
writer.Write(InventoryArray[i, j]);
}
writer.WriteLine();
}
}
The using will automatically flush and close the file, and dispose the StreamWriter.
1 option is already there, but need another
using (StreamReader str = new StreamReader(#"d:\alfa.txt", Encoding.Default))
{
for (int i = 0; i <= 4; i++)
{
Line = str.ReadLine();
}
}
You can use File.ReadLines method and simple linq
int count = File.ReadLines(#"d:\alfa.txt").Count();
Better I think to use file.Simple ReadLines method and linq in
int count = File.ReadLines(#"d:\alfa.txt").Count();
Until you reach the end of stream.
int count = 0;
using (StreamReader str = new StreamReader(#"d:\alfa.txt", Encoding.Default))
{
while(!str.EndOfStream)
{
Line = str.ReadLine();
count++:
}
}
If the string is the sentence :
if(mas[i] == '.') count++;
You must copy the file from all the characters in the mas and then check the condition .
I am trying to write one line of text 75 times and increase the number by 1 till it hits the 75 condition. Starting at 2 for a reason.
Here's the code
class WriteTextFile
{
static void Main()
{
string path = "C:\\Users\\Writefile\\test.txt";
string line;
int i = 2;
while (i <= 75 )
{
line = "Error_Flag = 'FOR_IMPORT' and location_type = 'Home' and batch_num = " + i + "\n";
System.IO.File.WriteAllText(#path, line);
i++;
}
}
}
With this, it just writes one line with 75 at the end. I want it to write all 74 lines with the same thing, only the number goes up every time. Thanks.
System.IO.File.WriteAllText will overwrite the contents of the file each time.
What you probably should do is use a StreamWriter:
using (var sw = new System.IO.StreamWriter(path))
{
for (var i = 2; i <= 75; i++)
{
sw.WriteLine("Error_Flag = 'FOR_IMPORT' and location_type = 'Home' and batch_num = {0}", i);
}
}
This will automatically create the file, write all the lines, and then close it for you when it's done.
Don't use File.WriteAllText because this generates a new file every time.
Instead try something like this:
using (var writer = new StreamWriter("filename.txt"))
{
for(int x = 2; x <= 75; x++)
{
writer.WriteLine("Error_Flag = 'FOR_IMPORT' and location_type = 'Home' and batch_num = " + x);
}
}
You're overwriting the file on each new write operation. Consider appending to it.
Here's my code:
for (int j = 0; j < bufferreader.Length; j++)
{
using (StreamWriter sw = File.AppendText(#"C:\Users\yamald\Documents\Normal.data"))
{
//sw.Write();
if (bufferreader.length != null)
{
sw.Write(bufferreader[j] + ",");
}
else
{
sw.WriteLine("\n");
}
}
}
How can I write a "\n" at the end of array to my file? The else command does not run.
You need to place sw.WriteLine("\n"); after the for loop.
As the loop stops when j = bufferreader.length, the if statement is always true.
Also, I think that bufferreader.length will never be null as you never modify this variable. I think what you need is :
if (bufferreader.length > j)
You should probably just make the StreamWriter object before everything else and have it available until the loop has finished, then just write the newline after the loop, like this:
using (StreamWriter sw = File.AppendText(#"C:\Users\yamald\Documents\Normal.data"))
{
for (int j = 0; j < bufferreader.Length; j++)
{
sw.Write(bufferreader[j] + ",");
}
sw.WriteLine("\n");
}
It's also probably better to use a while loop and do something like while(bufferreader.length != null) instead of the for loop and if statement, but that's up to you and I haven't used bufferreader in a while so wouldn't know the exact syntax for that.
However, the reason for why the else never gets executed is (as EoiFirst correctly said) that you're not actually changing bufferreader.length so it won't ever be null.