-
begginer help
hi i want to remove a file extension from a string how can i do this ?
DirectoryInfo di = new DirectoryInfo(@"threads/");
FileInfo[] threads = di.GetFiles("*.aspx");
foreach (FileInfo file in threads)
{
string x = file.Name;
char[] y = x.ToCharArray();
int i = x.Length;
char[] j;
int t = 0;
while (t < (i - 4))
{
j[t] = y[t];
t++;
}
Literal1.Text = "<a href=" + x +">" + x + "</a>";
}
-
Re: begginer help
Try using this code,.
You can modify it as per your requirement. I wrote it show you how to split up the filename and extension.
DirectoryInfo di = new DirectoryInfo(@"threads/");
);
FileInfo[] threads = di.GetFiles("*.aspx");
foreach (FileInfo f in threads)
{
string[] arFileName= f.Name.Split('.');
string FileName = arFileName[0];
string Extension = arFileName[1];
}
-
Re: begginer help
Or, a better way to do it:
Code:
string name = System.IO.Path.GetFileNameWithoutExtension( filename );
No need to reinvent the wheel on this one.
-
Re: begginer help
Yes System.IO.File has enough functions to deal with all this - and moreover splitting by . may not work all the time . The best way to do it is by using GetFileNameWithoutExtension()
-
Re: begginer help
Exactly. This file name is perfectly legal and MKohli's suggestion could not handle it
Code:
SomeFile.whatever.txt
-
Re: begginer help
Yupp.... You are correct.
-
Re: begginer help
That said, if you wanted to see what that method does it just uses LastIndexOf('.') instead and has a bit more error checking. This is the implementation:
Code:
public static string GetFileNameWithoutExtension(string path)
{
path = GetFileName(path);
if (path == null)
{
return null;
}
int length = path.LastIndexOf('.');
if (length == -1)
{
return path;
}
return path.Substring(0, length);
}