C#如何通过文本文件查找特定值

时间:2013-07-30 19:50:29

标签: c# text

我试图弄清楚如何浏览文本文件,其中的内容格式如下:

Date: 7/30/2013 12:00:00 AM 
Source Path: C:\FileMoveResults 
Destination Path: C:\Users\Documents\.NET Development\testing\ 
Last Folder Updated: 11.0.25.1

我可以根据“上次更新的文件夹”搜索它,并将源路径和目标路径存储在单独的变量中。

怎么会这样做呢?

谢谢!

编辑:

这是我目前所拥有的代码,因为我收到的错误是“foreach不支持bool”,所以它不起作用

using (var reader = new StreamReader(GlobalVars.strLogPath))
{
foreach (var items in File.ReadLines(GlobalVars.strLogPath))
{
foreach(var item in items.StartsWith("Destination Path: "))
{
//nothing here yet

4 个答案:

答案 0 :(得分:4)

  • 一次阅读4行
  • 解析最后一行(最后更新的文件夹)
  • 检查是否要存储条目
  • 如果是 - >商店第2行和第3行
  • 重复直到不再有可用的行

修改:反映您对代码的新问题:

删除最里面的foreach循环并将“items”重命名为“oneSingleLine” - 这样可以更清楚地显示错误所在的位置。也许会创建一个新问题,因为这不是讨论板。

答案 1 :(得分:0)

我在想这样的事情。它有点复杂但有助于确保如果文件格式发生变化,您仍然可以循环查找每组值。

    public void ReadFile(string filepath)
    {
        Dictionary<string, string> mypaths = new Dictionary<string, string>();
        string line;
        string line1 = null;
        string line2 = null;
        bool store = false;
        using(var rdr = new StreamReader(filepath))
        {
            while((line = rdr.ReadLine()) != null)
            {
                if(store = false && line.ToLower().Contains("source path:"))
                {
                    line1 = line;
                    store = true;
                }
                else if (store = true && line.ToLower().Contains("destination path:"))
                {
                    line2 = line;
                }
                else if (line.ToLower().Contains("last folder updated:"))
                {
                    var myvaluetoinspect = line;
                    if(1==1) // my condition
                    {
                        mypaths.Add(line1, line2);
                    }
                    // Clear and start over
                    store = false;
                    line1 = null;
                    line2 = null;
                }
                else
                {
                    store = false;
                    line1 = null;
                    line2 = null;
                }
            }
        }
    }

答案 2 :(得分:0)

这是一个如何做到的例子。 在处理格式错误的线条等方面,这里有很大的改进空间。

    static void ReadFile(string path)
    {
        var lines = System.IO.File.ReadAllLines(path).ToList();
        var infos = new List<TextFileInfo>();

        var info = new TextFileInfo();
        var currentLine = 0;
        while (lines.Count > 0)
        {
            TryReadLine(lines[0], info);

            if (currentLine++ >= 3)
            {
                currentLine = 0;
                infos.Add(info);
                info = new TextFileInfo();
            }

            lines.RemoveAt(0);
        }

        //Do something with infos
        // return infos;
   }

    public static void TryReadLine(string line, TextFileInfo info)
    {
        if (line.StartsWith(DateTag))
        {
            var value = line.Replace(DateTag, string.Empty).Trim();
            info.Date = DateTime.Parse(value);

            return;
        }

        if (line.StartsWith(SourcePathTag))
        {
            var value = line.Replace(SourcePathTag, string.Empty).Trim();
            info.SourcePath = value;

            return;
        }

        if (line.StartsWith(DestinationPathTag))
        {
            var value = line.Replace(SourcePathTag, string.Empty).Trim();
            info.DestinationPath = value;

            return;
        }

        if (line.StartsWith(LastFolderUpdatedTag))
        {
            var value = line.Replace(SourcePathTag, string.Empty).Trim();
            info.LastFolderUpdated = value;

            return;
        }

        throw new Exception("Invalid line encountered");
    }

    public class TextFileInfo
    {
        public DateTime Date { get; set; }
        public string SourcePath { get; set; }
        public string DestinationPath { get; set; }
        public string LastFolderUpdated { get; set; }
    }

答案 3 :(得分:0)

以下是如何使用LINQ执行此操作的示例启动器。我使用LinqPad来玩代码。

    var input = "Date: 7/30/2013 12:00:00 AM\nSource Path: C:\\FileMoveResults\nDestination Path: C:\\Users\\Documents\\.NET Development\\testing\\ \nLast Folder Updated: 11.0.25.1 \nDate: 7/30/2013 12:00:00 AM\nSource Path: C:\\FileMoveResults\nDestination Path: C:\\Users\\Documents\\.NET Development\\testing\\ \nLast Folder Updated: 11.0.25.1 \nDate: 7/30/2013 12:00:00 AM\nSource Path: C:\\FileMoveResults\nDestination Path: C:\\Users\\Documents\\.NET Development\\testing\\ \nLast Folder Updated: 11.0.25.1 \nDate: 7/30/2013 12:00:00 AM\nSource Path: C:\\FileMoveResults\nDestination Path: C:\\Users\\Documents\\.NET Development\\testing\\ \nLast Folder Updated: 11.0.25.1 \nDate: 7/30/2013 12:00:00 AM\nSource Path: C:\\FileMoveResults\nDestination Path: C:\\Users\\Documents\\.NET Development\\testing\\ \nLast Folder Updated: 11.0.25.1 \nDate: 7/30/2013 12:00:00 AM\nSource Path: C:\\FileMoveResults\nDestination Path: C:\\Users\\Documents\\.NET Development\\testing\\ \nLast Folder Updated: 11.0.25.1 \nDate: 7/30/2013 12:00:00 AM\nSource Path: C:\\FileMoveResults\nDestination Path: C:\\Users\\Documents\\.NET Development\\testing\\ \nLast Folder Updated: 11.0.25.1 \nDate: 7/30/2013 12:00:00 AM\nSource Path: C:\\FileMoveResults\nDestination Path: C:\\Users\\Documents\\.NET Development\\testing\\ \nLast Folder Updated: 11.0.25.1 \nDate: 7/30/2013 12:00:00 AM\nSource Path: C:\\FileMoveResults\nDestination Path: C:\\Users\\Documents\\.NET Development\\testing\\ \nLast Folder Updated: 11.0.25.1";

string[] lines = null;
using(var reader = new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(input))))
{
    lines = reader.ReadToEnd().Split('\n');
}

IList<Tuple<string, string>> paths = new List<Tuple<string, string>>();
if(lines != null)
{
    const int TAKE = 4;

    var position = 0;

    while(position < lines.Length)
    {
        var currentLines = lines.Skip(position).Take(TAKE);
        paths.Add(Tuple.Create(currentLines.ElementAt(1).Replace("Source Path: ", string.Empty), currentLines.ElementAt(2).Replace("Destination Path: ", string.Empty)));
        position = (position + TAKE);
    }
}

paths.Dump("Result");

我所做的是收集所有源路径和目标路径。您可以修改此选项,仅根据搜索条件存储所需的内容。

结果看起来像这样,我只是反复复制你的例子,所以路径名没有变化:

enter image description here

如果你想在对象中内置移动和复制功能,我可能也会制作Tuple<DictionaryInfo, DictionaryInfo>类型的元组。