简体   繁体   English

如何从c#中的文本文件中读取和获取特定内容?

[英]how to read and get specific content from a text file in c#?

i have text file as testfile.txt content as below:我有文本文件作为 testfile.txt 内容如下:

abc.com

test/test1/testdata.gif

xyz.com 

test2/test3/xyzdata.gif

i want to read this mentioned file and save with below in new file as giftextfile.txt and content should be我想阅读这个提到的文件并在新文件中保存为gifextfile.txt,内容应该是

testdata.gif

xyzdata.gif

i have tried below code:我试过下面的代码:

  using (var sr = new StreamReader(fileName)) {
          for (int i = 1; i < line; i++)
          sr.ReadLine().Where(x=>x.Equals(".gif")).SkipWhile                    (y=>y!='/');

can anyone help please?有人可以帮忙吗? thanks in advance!提前致谢!

So you have a text-file that contains Urls and images and you want the name of the images?所以你有一个包含 URL 和图像的文本文件,你想要图像的名称?

using System.IO;
// ...

var images = File.ReadLines(fileName)
    .Where(f => Path.GetExtension(f).Equals(".gif", StringComparison.InvariantCultureIgnoreCase)) // for example
    .Select(f => Path.GetFileName(f));
File.WriteAllLines(newFileName, images);

Edit: Simplest Approach编辑:最简单的方法

  1. Read the input file, line by line逐行读取输入文件
  2. Check if the line contains .gif检查该行是否包含 .gif
  3. Write only the file name to new file只将文件名写入新文件

Code代码

StreamReader reader = File.OpenText(fileName);
FileInfo outputFileInfo = new FileInfo("output.txt");
StreamWriter output = outputFileInfo.CreateText();
string line = null;
while ((line = reader.ReadLine()) != null)
{
    if (line.IndexOf(".gif", StringComparison.CurrentCultureIgnoreCase) > -1)
    {
        output.WriteLine(Path.GetFileName(line));
    }
}
reader.Close();
output.Close();

Optimized Solution, Inspired from @Matthew Watson comment优化的解决方案,灵感来自@Matthew Watson 评论

It does the same thing only difference is using lambda expression in LINQ's它做同样的事情,唯一的区别是在 LINQ 中使用 lambda 表达式

  1. File.ReadLines read all lines and reruns enumerable string File.ReadLines 读取所有行并重新运行可枚举字符串
  2. Here we can directly use the where filter which lambda expression to pick only those items that end with .gif这里我们可以直接使用 where 过滤器 which lambda 表达式只选择那些以 .gif 结尾的项目
  3. Finally, use the Path.GetFileName(string) to extract only name最后,使用 Path.GetFileName(string) 只提取名称
  4. We can then use File.WriteAllLines in one shot the final output然后我们可以一次性使用 File.WriteAllLines 最终输出

Optimized Code优化代码

var filenames = File.ReadLines(fileName)
            .Where(line => line.EndsWith(".gif", StringComparison.OrdinalIgnoreCase)).Select(Path.GetFileName);
File.WriteAllLines("output.txt", filenames);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM