C# Cannot use Streamwriter on a txt file in C# Properties.Resources - c#

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.

Related

Export c# array to csv file with title

I tried to export an 2-D array from c# to a csv file but last several rows are missing in the csv file.I don't know where the problem is in my code.
First,I'd like to know if my code is not correct?
Second,is it possible to add a title for each row in the csv file .
Thanks in advance
Here is an example of my array in c#
string[,] array=new string[]{{2000,2},{2001,4}}
I want to a result like this in csv file with title
Date C1
2000 2
2001 4
My code:
var outfile=new.streamwriter(#"fileadress.csv");
for(int i=0;i<array.GetUpperbound(0);i++)
{
string content="";
for(int j=0;j<array.GetUpperbound(1);j++)
{
content+= array[i,j]+";";
}
outfile.WriteLine(content);
}
There are a lot of problems in the code shown. The most important is the wrong usage of GetUpperBound that return the 'upperbound' of your array, and your example this upperbound is 1 (not 2) thus the < array.UpperBound skips the last position in the array.
I suggest a reworking of your code in this way
// This is an array of strings right?
string[,] array=new string[,]{{"2000","2"},{"2001","4"}};
// Use a StringBuilder to accumulate your output
StringBuilder sb = new StringBuilder("Date;C1\r\n");
for (int i = 0; i <= array.GetUpperBound(0); i++)
{
for (int j = 0; j <= array.GetUpperBound(1); j++)
{
sb.Append((j==0 ? "" : ";") + array[i, j]);
}
sb.AppendLine();
}
// Write everything with a single command
File.WriteAllText(#"fileadress.csv", sb.ToString());

WriteLine to .txt for each line in richTextBox

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

Write a character at the end of an array

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.

For testing I would like to generate a lot of files with some content - any easy way?

Im using C# and my code is reading and moving some files. The problem is, that there are not so many files to read and move them to other folders. But I would like to test my code with 500,1000 or more files at once.
I could create every single file by myself -> not so smart. I could generate these files and write my own code for this -> could work, but is there not an easier way? Maybe there are already some tools for developers to create testfiles? Or is there another solution in c#/.net?
PS: Ah forgot to say - Im reading normal ascii file. Later I would like to create "csv-like" files (strings splittet by ";") if it would be possible.
This code will create an arbitrary number of files, each with an arbitrary number of lines, each containing an arbitrary number of comma-separated random integer values.
I hope it gets you started on creating some test data for your application.
static void Main(string[] args)
{
int numFiles = 30;
for (int fileIndex = 0; fileIndex < numFiles; fileIndex++)
{
string randomFileName = Path.Combine(#"c:\temp", Path.GetRandomFileName() + ".csv");
GenerateTestFile(randomFileName, 20, 10);
}
}
static void GenerateTestFile(string fileName, int numLines, int numValues)
{
int[] values = new int[numValues];
Random random = new Random(DateTime.Now.Millisecond);
FileInfo f = new FileInfo(fileName);
using (TextWriter fs = f.CreateText())
{
for (int lineIndex = 0; lineIndex < numLines; lineIndex++)
{
for (int valIndex = 0; valIndex < values.Length; valIndex++)
{
values[valIndex] = random.Next(100);
}
fs.WriteLine(string.Join(",", values));
}
}
}
var yourSampleTextStringArray = new[]{"dada","dada","aaa"/*.....*/};
var rnd = new Random();
for (int i = 0; i < 10e3; i++)
{
var temp = Path.GetTempFileName();
File.WriteAllLines(temp, yourSampleTextStringArray.Where(line => rnd.NextDouble() > 0.5));
}

String as a file name C#

I have a problem writing a program in C#.
I want to to save string variables from a ListBox1 to textfile, which is named after the item from ListBox2, like here:
Write = new StreamWriter(xxxxx);
for (int I = 0; I < ListBox1.Items.Count; I++)
{
Text = (SubCategories.Items[I]).ToString();
Write.WriteLine(Text);
}
Write.Close();
What should I replace xxxxx to have there ListBox2.SelectedItem, for example to make file "test.txt".
You can replace xxxxx with this:
var path = Path.Combine(Environment.CurrentDirectory, ListBox2.SelectedItem.ToString());
using (var writer = new StreamWriter(path))
{
for (int I = 0; I < ListBox1.Items.Count; I++)
{
Text = (SubCategories.Items[I]).ToString();
writer.WriteLine(Text);
}
}
You should use a using with IDisposable objects.

Categories

Resources