CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Thread: begginer help

  1. #1
    Join Date
    Jan 2011
    Posts
    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>";
    }

  2. #2
    Join Date
    Jan 2011
    Location
    Bangalore, India
    Posts
    4

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

    }

  3. #3
    Join Date
    Jun 2008
    Posts
    2,477

    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.

  4. #4
    Join Date
    Jul 2010
    Posts
    82

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

  5. #5
    Join Date
    Jun 2008
    Posts
    2,477

    Re: begginer help

    Exactly. This file name is perfectly legal and MKohli's suggestion could not handle it

    Code:
    SomeFile.whatever.txt

  6. #6
    Join Date
    Jan 2011
    Location
    Bangalore, India
    Posts
    4

    Re: begginer help

    Yupp.... You are correct.

  7. #7
    Join Date
    Jun 2008
    Posts
    2,477

    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
  •  





Click Here to Expand Forum to Full Width

Featured