{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
I have a array which located in the file , how can I read it using C sharp?
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
I have a array which located in the file , how can I read it using C sharp?
Read the line into a string. Lose the curlies, split on commas, cast each token into an integer and append it to a List. Finally use ToArray() to get back an int[]
Look at the System.IO.File and System.String type documentation in MSDN. You should find members to help you accomplish your goal.
Well, I would probably use a different format, but...
using ( Stream stream = new FileStream( @"C:\foo.txt", FileMode.Open ) )
using ( TextReader reader = new StreamReader( stream ) )
{
string contents = reader.ReadToEnd( );
contents = contents.Replace( "{", "" ).Replace( "}", "" );
var values = new List<int>();
foreach ( string s in contents.Split( ',' ) )
{
try
{
values.Add( int.Parse( s ) );
}
catch ( FormatException fe )
{
// ...
}
catch ( OverflowException oe )
{
// ...
}
}
}
You can use Regex and LINQ to pull a nice one liner:
List<int> data = Regex.Matches(
File.ReadAllText("data.txt"),
@"(\d+)")
.Cast<Match>()
.Select(i => Convert.ToInt32(i.Value))
.ToList();
Your sample file makes me think JSON. If that's the case, then JSON.NET could be an effective option.
The complete answer depends on a lot of things, but it sounds like these are you the steps you need to figure out:
As for how to specifically do each of these, I suspect you can find many resources here on SO and in other locations to find the details. But you're probably looking for a StreamReader, String.Split, Int32.Parse and a List<int>.
I'd recommend looking up the String.Split(char[]) method.
It allows you to take a string and split it into an array of strings based on the characters you pass in (in your case ", "). For the first element in the array you'd need to remove the { and for the last element, remove the }. There is a String.Remove() method for this.
Finally you will need to convert each string into an integer. You can do this with a for each loop and int.TryParse()
TryParse will let you know if it is actually an integer or not, it's good practice to never assume your input is valid. You're program shouldn't crash because it reads in some bad data.
To actually open the file and read the text, look up StreamReader/File.ReadAllText