尝试使用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中,但我不确定正则表达式有什么问题。有没有更有效的方法来做到这一点?
答案 0 :(得分:0)
这不是一个有效的表达式,它的说法与*
之前的任何字符匹配0次或更多次,因为在出现问题之前没有字符。
这可能与大多数事情相匹配,但不包括特殊字符。
Regex regex = new Regex("[a-zA-Z0-9]{1,}.csv");
您也可以这样做:
if(test.EndsWith(".csv"))
最后,我会将您的数组更改为List<T>
或类似的内容,这里将进一步解释: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<T>
位于System.Collections.Generic