I'm creating programming to write and read values.
But I couldn't find how to write and read "arrays" using StreamWriter and StreamReader.
I would appreciate if you give me the answer.
using System;
using static System.Console;
using System.IO;
using System.Text;
namespace writeReadArray
{
public class Record
{
public void WriteFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Create,FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Close();
fs.Close();
}
public void ReadFile(string filename)
{
FileStream infile = new FileStream(filename, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(infile);
reader.Close();
infile.Close();
}
}
}
The array is in another class.
using System;
using static System.Console;
namespace writeReadArray
{
public class Arrays
{
private char[] AlphabetValues = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
}
}
CodePudding user response:
You need to consider what you mean by "array". In the trivial sense you can just use the write method that takes a char-array, or convert the char-array to a string using new string(AlphabetValues)
and write that. Reading would be done by using ReadLine or ReadToEnd.
But if you want to read and write multiple distinctive values separated from each other and other kinds of content you need some kind of separators to separate each value from each other and from any other content. This can be problematic when dealing with arrays of strings or characters, since our separator character(s) might occur in the strings we are storing, so we would need to replace these characters by some sequence of other characters, a process known as "escaping".
This is super annoying when dealing with floating point numbers, since using ',' as the separator would be very natural, i.e. "1.2, 3.4", but ',' is also used as the decimal separator for some cultures, so could result in "1,2, 3,4 if you are not careful.
So for more complex content you might be better of using existing serialization libraries, like json, that takes care of all this for you. Or use some kind of binary serialization if you do not need the data to be humanly readable.
CodePudding user response:
1-Write
char[] AlphabetValues = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
`FileStream sb = new FileStream("MyFile.txt", FileMode.OpenOrCreate);` `StreamWriter sw = new StreamWriter(sb);` `sw.Write(AlphabetValues);` `sw.Close();`
2-Read
string path = @"c:\temp\MyFile.txt";
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}