【问题标题】:How can I write the result to the csv?如何将结果写入 csv?
【发布时间】:2020-04-08 21:21:21
【问题描述】:

我想 ping csv 中的主机名并将结果写入下一列,但我有点不知所措?

这是我得到的错误:Error CS0021 Cannot apply indexing with [] to an expression of type 'StreamReader'

而我唯一能做的就是将 csv 中的内容写入控制台。

    string filePath = @"c:\hostnames.csv";
    var reader = new StreamReader(filePath);
    Ping ping = new Ping();
    List<string> hostnames = new List<string>();
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        var values = line.Split(',');
        hostnames.Add(values[0]);
        hostnames.ForEach(Console.WriteLine);
    }

    List<string> goodPing = new List<string>();
    foreach (string singleComputer in hostnames)
    {
        PingReply pingresult = ping.Send(singleComputer);

        if (pingresult.Status.ToString() == "Success")
        {
            goodPing.Add(singleComputer);
        }
    }
        var csv = new StringBuilder();
        var first = reader[0].ToString();   
        var newLine = string.Format("{0}");
        csv.AppendLine(newLine);
        File.WriteAllText(filePath, csv.ToString());
    }

【问题讨论】:

  • 您遇到了什么错误?我看到有一个额外的 { .. 请更新您的帖子并说明您尝试了什么错误,以便人们可以更好地帮助您
  • 我更新了问题。
  • 您能否举例说明您的 hostnames.csv 文件现在的样子以及您希望它完成后的样子?

标签: c# csv streamreader streamwriter


【解决方案1】:

目前尚不清楚您遇到了什么错误,但我注意到的一个问题是您没有为 string.Format 提供变量,我认为它在那里没用..

我假设的示例 hostnames.csv 是这样的:

www.google.com,www.somebadu-rlwhichcannot..com,www.stackoverflow.com

        var filePath = @"c:\test\hostnames.csv"; // change it to your source
        var filePathOutput = @"c:\test\hostnamesOutput.csv"; // use separate output file so you would not overwrite your source..
        var ping = new Ping();
        var hostNames = new List<string>();

        using (var reader = new StreamReader(filePath))
        {
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                hostNames = line.Split(',').ToList();
            }
        }

        var goodPing = new List<string>();

        foreach (var singleComputer in hostNames)
            try
            {
                var pingResult = ping.Send(singleComputer);
                if (pingResult.Status == IPStatus.Success)
                {
                    goodPing.Add(singleComputer);
                }
            }
            catch (Exception e)
            {
                // host was not in a correct format or any other exception thrown....
                // do whatever error handling you want, logging etc...
            }

        var csv = new StringBuilder();

        foreach (var hostname in hostNames)
        {
            var resultText = goodPing.Contains(hostname) ? "Success" : "Failed";
            var newLine = string.Format("{0},{1}", hostname, resultText);
            csv.AppendLine(newLine);
        }

        File.WriteAllText(filePathOutput, csv.ToString());

我没有在 IDE 上尝试过,但它应该做你想做的事情。似乎您从某个地方复制粘贴了该代码并试图在不理解的情况下对其进行操作。我建议确保您在开始使用它之前逐行理解它为什么使用它,如何使用它。否则,您将始终需要有人为您编写代码!

输出将是(在 excel 中):

【讨论】:

    【解决方案2】:

    这是我认为您正在尝试做的简化版本。

    代码运行前的 hostheaders.csv 示例

    www.google.com
    www.stackoverflow.com
    www.fakewebsitehere.com
    

    更新代码

    string filePath = @"c:\hostnames.csv";
    List<string> results = new List<string>();
    
    using (var reader = new StreamReader(filePath))
    {
        Ping ping = new Ping();
    
        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            var values = line.Split(',');
            var hostname = values[0];
            Console.WriteLine(hostname);
    
            PingReply pingresult = ping.Send(hostname);
    
            results.Add($"{line},{pingresult.Status.ToString()}");
        }
    }
    
    File.WriteAllLines(filePath, results);
    

    代码运行后的hostheaders.csv

    www.google.com,Success
    www.stackoverflow.com,Success
    www.fakewebsitehere.com,TimedOut
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 2013-09-24
      • 2011-09-30
      • 1970-01-01
      相关资源
      最近更新 更多