简体   繁体   中英

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

i have text file as testfile.txt content as below:

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

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?

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
  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

It does the same thing only difference is using lambda expression in LINQ's

  1. File.ReadLines read all lines and reruns enumerable string
  2. Here we can directly use the where filter which lambda expression to pick only those items that end with .gif
  3. Finally, use the Path.GetFileName(string) to extract only name
  4. We can then use File.WriteAllLines in one shot the final output

Optimized Code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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