Search code examples
c#filefile-ioclasspathfilenames

How to get just a File Name from the full path?


I can't believe I'm having to ask this, because there's simple questions & then there's ridiculous questions .. Anyway, I'm actually unable to find out the answer due to the obvious answer (not the one I'm looking for).

I have code like this :

 OpenFileDialog ofd = new OpenFileDialog();
            if(ofd.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = ofd.FileName;
            }

This works good, because then I have a method, that of course, opens my file (different form). However, to pass this to my other form's viewing method the path (ofd.FileName) must remain in full.

My question, or problem is : How to get just the file's actual name from the path? I have tried this : textBox1.Text = ofd.FileName.LastIndexOf("\"); The above attempt flagged as an error within the compiler because a back-slash is classed as a newline.

So, how can I gain the file name from the path? for instance, lets say the file's name is : List1.text, I would want my 2nd forms textBox1.Text to be : List1.text , rather than the full path.

Thanks in advance ! !


Solution

  • You can use Path.GetFileName Method in Path Class:

    string fileName = @"C:\mydir\myfile.ext";
    string path = @"C:\mydir\";
    string result;
    
    result = Path.GetFileName(fileName);
    Console.WriteLine("GetFileName('{0}') returns '{1}'", 
        fileName, result);
    
    result = Path.GetFileName(path);
    Console.WriteLine("GetFileName('{0}') returns '{1}'", 
        path, result);
    
    // This code produces output similar to the following: 
    // 
    // GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext' 
    // GetFileName('C:\mydir\') returns ''
    

    if you want to get extension you can use Path.GetExtension Method:

    string fileName = @"C:\mydir.old\myfile.ext";
    string path = @"C:\mydir.old\";
    string extension;
    
    extension = Path.GetExtension(fileName);
    Console.WriteLine("GetExtension('{0}') returns '{1}'", 
        fileName, extension);
    
    extension = Path.GetExtension(path);
    Console.WriteLine("GetExtension('{0}') returns '{1}'", 
        path, extension);
    
    // This code produces output similar to the following: 
    // 
    // GetExtension('C:\mydir.old\myfile.ext') returns '.ext' 
    // GetExtension('C:\mydir.old\') returns ''