【问题标题】:How can I read data from specific location in .asc file using c#如何使用 c# 从 .asc 文件中的特定位置读取数据
【发布时间】:2017-01-11 08:40:54
【问题描述】:

我有 .asc 文件,其中有 1000 行。行中的每一列都是固定长度的,并且由一个空格分隔。我想读取从 296 位置开始并连续到 326 位置结束的电子邮件 id 列。

有没有办法从 .asc 文件中读取这些数据?

【问题讨论】:

  • 什么是“.asc”文件?它使用什么编码?文件中的行真的是固定宽度(以字节为单位)吗?您是要读取特定行还是所有行?
  • 缺少要解析的文件的示例或描述,您可以在fixed width mode 中使用TextFieldParser 吗?尽管位于 Microsoft.VisualBasic.FileIO 命名空间中,但它在 c# 中完全可用。参见例如csharphelper.com/blog/2012/05/….

标签: c# c#-4.0 c#-3.0 c#-2.0


【解决方案1】:

这可能对你有用。我只是在读取文件中的电子邮件 ID,无论它可能是我的扩展文件,可能是 txt 或 asc。此外,电子邮件地址是否位于其他位置而不是 296 或 326 也没关系。

public void ExtractAllEmails()
{
    string datafrmAsc = File.ReadAllText(YourASCFile); //read File 
    Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
    MatchCollection emailMatches = emailRegex.Matches(datafrmAsc);
    StringBuilder sb = new StringBuilder();
    foreach (Match emailMatch in emailMatches)
    {
        sb.AppendLine(emailMatch.Value);
    }
    File.WriteAllText(SomeTxtFile, sb.ToString());
}

【讨论】:

  • 对 SO 表示感谢的另一种方式是支持答案。好吧,很高兴为您提供帮助,非常欢迎您。 :)
【解决方案2】:

假设这是一个大文本文件,你可以这样做:

        List<string> emailsList = new List<string>();
        int startIndex = 295;
        int endIndex = 325;

        using (FileStream stream = File.Open("c:\\test.asc", FileMode.Open))
        using (StreamReader sr = new StreamReader(stream))
        {
                string line = string.Empty;
                while ((line = sr.ReadLine()) != null)
                {
                    emailsList.Add(line.Substring(startIndex, endIndex - startIndex).Trim());
                }

         }

【讨论】:

  • 谢谢尼诺。虽然早期的代码解决了我的问题。但是您的代码仍然进行了一些优化。我有不同的实现方式,所以也会使用你的代码。
  • 很高兴我能帮上忙。我的方法更加优化(它逐行读取文件,而@Mohit Shrivastava 一次加载所有文本),因为您说有数千行。
  • 实际上我已经为处理定义了批处理大小,因此您的代码符合我的要求。虽然优化在这里意味着的不是性能,而是处理方法。
猜你喜欢
  • 2017-02-12
  • 2012-06-13
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多