通读流阅读器并使用行中的一些文本

时间:2014-02-25 14:55:43

标签: c# asp.net asp.net-mvc-3 stream inputstream

使用streamReader读取文件。
如果该行以1开头,我想使用此行 该行的内容如下:1,103,1,4454:HH

所以我想在第一个,之后但在第二个之前获取数字。所以我需要103并将其分配给ProductId:

int ProductID;

using (StreamReader sr = new StreamReader(fakeFileToProcess))
{
    while (!sr.EndOfStream)
    {
        string line = sr.ReadLine();

        if (line.StartsWith("1,"))
        {
            //so line will be 1,103,1,44543:HH
            //How do I capture the '103'...something like:
            //ProductID = line.read between "1," & ","(next comma)

        }

        if (line.StartsWith("25"))
        {
            continue;
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用String.Split()功能来实现此目的:

来自MSDN: String.Split()

  

返回包含此字符串中子字符串的字符串数组   由指定字符串数组的元素分隔。一个   参数指定是否返回空数组元素。

试试这个:

string num = line.Split(',')[1].Trim();
if(int.TryParse(str,out ProductID)
{
   //success now ProductID contains int value (103)
}

完整代码:

int ProductID;    
using (StreamReader sr = new StreamReader(fakeFileToProcess))
{
    while (!sr.EndOfStream)
    {
        string line = sr.ReadLine();

        if (line.StartsWith("1,"))
        {
            string num = line.Split(',')[1].Trim();
            if(int.TryParse(str,out ProductID)
            {
                //parsing is successful, now ProductID contains int value (103)
            }    
        }

        if (line.StartsWith("25"))
        {
            continue;
        }
    }
}

答案 1 :(得分:1)

如果有明确的分隔数据,请使用string.IndexOf IndexOf比在其部分中拆分字符串更好,因为您不需要创建字符串数组

   if (line.StartsWith("1,"))
   {
       // search the second comma after  the first one....
       int pos = line.IndexOf(',', 2);

       // for simplicity, do not check if you really have found a second comma....
       string id = line.Substring(2, pos - 2);

       // Try to convert whatever is between the first comma and the second one..
       if(Int32.TryParse(id, out productID))
           Console.WriteLine("Got it:" + productID.ToString());

   }

答案 2 :(得分:0)

您可以使用string.Split()方法来实现您的目标。 要转换为int,请使用int.Parse()方法。

所以你可以做到以下几点:

List<string> items = line.Split(',');
ProductID = int.Parse(items[1]);