Reputation: 1
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!
Upvotes: 0
Views: 987
Reputation: 1205
Edit: Simplest Approach
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
Optimized Code
var filenames = File.ReadLines(fileName)
.Where(line => line.EndsWith(".gif", StringComparison.OrdinalIgnoreCase)).Select(Path.GetFileName);
File.WriteAllLines("output.txt", filenames);
Upvotes: 0
Reputation: 460028
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);
Upvotes: 2