【问题标题】:Verifying and parsing csv to 2D array in C# Visual Studios在 C# Visual Studios 中验证和解析 csv 为二维数组
【发布时间】:2014-04-19 05:43:49
【问题描述】:

只是尝试 C# 来制作一个加载 csv 文件的按钮来验证它们并解析它们:

protected void Upload_Btn_Click(object sender, EventArgs e)
{
    string test = PNLdataLoader.FileName;
    //checks if file is csv
    Regex regex = new Regex("*.csv");
    Match match = regex.Match(test);
    if (match.Success)
    {
        string CSVFileAsString = System.Text.Encoding.ASCII.GetString(PNLdataLoader.FileBytes);
        System.IO.MemoryStream MS = new System.IO.MemoryStream(PNLdataLoader.FileBytes);
        System.IO.StreamReader SR = new System.IO.StreamReader(MS);
        //Store each line in CSVlines array of strings
        string[] CSVLines = new string[0];
        while (!SR.EndOfStream)
        {
            System.Array.Resize(ref CSVLines, CSVLines.Length + 1);

            CSVLines[CSVLines.Length - 1] = SR.ReadLine();

        }
    }

到目前为止,我已经将这些行存储在 CSVLines 中,但我不确定正则表达式有什么问题。有没有更有效的方法来做到这一点?

【问题讨论】:

  • 我没有看到二维数组,是不是漏掉了什么?
  • @MarkF 我还没有进入那部分,但仍在查看有关如何操作的文档。

标签: c# regex csv


【解决方案1】:

这不是一个有效的表达式,它的意思是匹配 * 之前出现的任何字符 0 次或更多次,因为在此之前没有字符存在问题。

这可能会匹配大多数东西,它不包括特殊字符。

Regex regex = new Regex("[a-zA-Z0-9]{1,}.csv"); 

您也可以这样做:

if(test.EndsWith(".csv"))

最后,我会将您的数组更改为 List&lt;T&gt; 或类似的东西,在此进一步解释:What is more efficient: List<T>.Add() or System.Array.Resize()?

//Store each line in CSVlines array of strings
List<string> CSVLines = new List<string>();
while (!SR.EndOfStream)
{
    CSVLines.Add(SR.ReadLine());

}

编辑: List&lt;T&gt; 在System.Collections.Generic中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多