Reputation: 411
I need to read a local text file which will have a file name on every line. Every file name needs to be trimmed of it's extension. When I get to the part where I need to save the result of the trimming to another array I'm having some trouble.
So far I have:
string path = @"C:\Users\path\file.txt";
string[] readText = File.ReadAllLines(path);
foreach (string s in readText)
{
string result = Path.GetFileNameWithoutExtension(s);
//here I can print the result to the screen
//but I don't know how to save to another array for further manipulation
}
If you need any further clarification I will do my best to be more clear. Thanks in advance.
Upvotes: 2
Views: 416
Reputation: 5514
Use a for
loop instead of foreach
:
string path = @"C:\Users\path\file.txt";
string[] readText = File.ReadAllLines(path);
for( int i = 0; i < readText.Length; i++ )
readText[i] = Path.GetFileNameWithoutExtension( readText[i] );
Upvotes: 3
Reputation: 75585
Allocate a new array of the same size as the original array, and then insert by indexing.
string path = @"C:\Users\path\file.txt";
string[] readText = File.ReadAllLines(path);
string[] outputArray = new string[readText.Length];
int index = 0;
foreach (string s in readText)
{
outputArray[index++] = Path.GetFileNameWithoutExtension(s);
}
Upvotes: 0
Reputation: 98826
You can also do this with Linq:
var path = @"C:\Users\path\file.txt";
var trimmed =
File.ReadAllLines(path)
.Select(Path.GetFileNameWithoutExtension)
.ToArray();
Upvotes: 4