|
-
January 12th, 2011, 06:55 AM
#1
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>";
}
-
January 12th, 2011, 09:17 AM
#2
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];
}
-
January 12th, 2011, 01:42 PM
#3
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.
-
January 14th, 2011, 12:12 AM
#4
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()
-
January 14th, 2011, 01:53 PM
#5
Re: begginer help
Exactly. This file name is perfectly legal and MKohli's suggestion could not handle it
Code:
SomeFile.whatever.txt
-
January 15th, 2011, 02:43 AM
#6
Re: begginer help
Yupp.... You are correct.
-
January 15th, 2011, 04:54 AM
#7
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);
}
Last edited by BigEd781; January 15th, 2011 at 02:36 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|