如何从C#中的文件中读取数组

时间:2021-12-05 21:22:04
{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?

我有一个位于文件中的数组,如何使用C sharp读取它?

6 个解决方案

#1


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 )
        {
            // ...
        }
    }
}

#2


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[]

将该行读入字符串。丢失curlies,在逗号上拆分,将每个标记转换为整数并将其附加到List。最后使用ToArray()来获取int []

Look at the System.IO.File and System.String type documentation in MSDN. You should find members to help you accomplish your goal.

查看MSDN中的System.IO.File和System.String类型文档。您应该找到帮助您实现目标的成员。

#3


You can use Regex and LINQ to pull a nice one liner:

您可以使用正则表达式和LINQ来拉出漂亮的衬垫:

List<int> data = Regex.Matches( 
    File.ReadAllText("data.txt"),
    @"(\d+)")
    .Cast<Match>()
    .Select(i => Convert.ToInt32(i.Value))
    .ToList();

#4


Your sample file makes me think JSON. If that's the case, then JSON.NET could be an effective option.

你的示例文件让我想到了JSON。如果是这种情况,那么JSON.NET可能是一个有效的选择。

#5


The complete answer depends on a lot of things, but it sounds like these are you the steps you need to figure out:

完整的答案取决于很多事情,但听起来这些是你需要弄清楚的步骤:

  • read in the file
  • 读入文件

  • split the contents into pieces
  • 将内容分成几部分

  • cast, convert or parse pieces into desired datatype
  • 转换,转换或解析成所需的数据类型

  • add to desired resulting collection
  • 添加到所需的结果集合

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>.

至于具体如何做这些,我怀疑你可以在SO和其他地方找到很多资源来查找细节。但是你可能正在寻找StreamReader,String.Split,Int32.Parse和List

#6


I'd recommend looking up the String.Split(char[]) method.

我建议查找String.Split(char [])方法。

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.

它允许您根据传入的字符(在您的情况下为“,”)将字符串拆分为一个字符串数组。对于数组中的第一个元素,您需要删除{和最后一个元素,删除}。这有一个String.Remove()方法。

Finally you will need to convert each string into an integer. You can do this with a for each loop and int.TryParse()

最后,您需要将每个字符串转换为整数。您可以使用for each和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.

TryParse会告诉你它是否实际上是一个整数,最好不要假设你的输入是有效的。你的程序不应该崩溃,因为它读取了一些不良数据。

To actually open the file and read the text, look up StreamReader/File.ReadAllText

要实际打开文件并阅读文本,请查找StreamReader / File.ReadAllText

#1


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 )
        {
            // ...
        }
    }
}

#2


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[]

将该行读入字符串。丢失curlies,在逗号上拆分,将每个标记转换为整数并将其附加到List。最后使用ToArray()来获取int []

Look at the System.IO.File and System.String type documentation in MSDN. You should find members to help you accomplish your goal.

查看MSDN中的System.IO.File和System.String类型文档。您应该找到帮助您实现目标的成员。

#3


You can use Regex and LINQ to pull a nice one liner:

您可以使用正则表达式和LINQ来拉出漂亮的衬垫:

List<int> data = Regex.Matches( 
    File.ReadAllText("data.txt"),
    @"(\d+)")
    .Cast<Match>()
    .Select(i => Convert.ToInt32(i.Value))
    .ToList();

#4


Your sample file makes me think JSON. If that's the case, then JSON.NET could be an effective option.

你的示例文件让我想到了JSON。如果是这种情况,那么JSON.NET可能是一个有效的选择。

#5


The complete answer depends on a lot of things, but it sounds like these are you the steps you need to figure out:

完整的答案取决于很多事情,但听起来这些是你需要弄清楚的步骤:

  • read in the file
  • 读入文件

  • split the contents into pieces
  • 将内容分成几部分

  • cast, convert or parse pieces into desired datatype
  • 转换,转换或解析成所需的数据类型

  • add to desired resulting collection
  • 添加到所需的结果集合

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>.

至于具体如何做这些,我怀疑你可以在SO和其他地方找到很多资源来查找细节。但是你可能正在寻找StreamReader,String.Split,Int32.Parse和List

#6


I'd recommend looking up the String.Split(char[]) method.

我建议查找String.Split(char [])方法。

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.

它允许您根据传入的字符(在您的情况下为“,”)将字符串拆分为一个字符串数组。对于数组中的第一个元素,您需要删除{和最后一个元素,删除}。这有一个String.Remove()方法。

Finally you will need to convert each string into an integer. You can do this with a for each loop and int.TryParse()

最后,您需要将每个字符串转换为整数。您可以使用for each和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.

TryParse会告诉你它是否实际上是一个整数,最好不要假设你的输入是有效的。你的程序不应该崩溃,因为它读取了一些不良数据。

To actually open the file and read the text, look up StreamReader/File.ReadAllText

要实际打开文件并阅读文本,请查找StreamReader / File.ReadAllText