Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • C# : How do I get the directory from a file's full path ?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 224
    Comment on it

    Many times in application development using C# it is required to get the directory from a file's full path.

    Let us say we need to find the directory for the following path:

       string path = @"C:\Directory\File.txt";
    

    If the requirement is to get the absolute path use the below:

      string absolutePath = Path.GetDirectoryName(path)
    

    If the requirement is to get relative name use the below:

       string relativeName =  FileInfo(path).Directory.FullName.
    

    If the requirement is to get the file name use the below:

    string filename = Path.GetFileName(path);

    If the requirement is to get the file name without extension use the below:

    string filenameNoExtension = Path.GetFileNameWithoutExtension(path);
    

    Note that Path and FileInfo are both found in the namespace System.IO.

    We should ensure that path is valid as below:

    1) The path parameter should not contain invalid characters, is empty, or contains only white spaces.

    2) The path parameter is not longer than the system-defined maximum length.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: