Thursday, December 13, 2012

Get Files in a Physical Directory


System.IO makes it possible to perform the Input/output operations in .NET. Here we are using it to access physical folder in the computer/server and get the file names/paths.

Below method does the following.

  • Get all files in a folder.
  • Get files with only the specified search term.
  • Get full file path.
  • Get only file name with extension.
  • Get only file name without extension.
  • Check file exists in the folder.
private void GetFiles()
    {
        string DPath = @"E:\MyFolder";
        string[] DirectoryFiles= Directory.GetFiles(DPath); // Get all files in the folder.
        string[] SearchDirectoryFiles = Directory.GetFiles(DPath,"*cli*"); // get only files which contains "cli" in the file name.

        foreach (string item in DirectoryFiles)
        {
            Response.Write(item.ToString() + "<br/>");//Get Full path.
        }

        foreach (string item in DirectoryFiles)
        {
            Response.Write(Path.GetFileName(item.ToString()) + "<br/>");//Get only file name with extention.
        }


        foreach (string item in DirectoryFiles)
        {
            Response.Write(Path.GetFileNameWithoutExtension(item.ToString()) + "<br/>");//Get only file  name with out extention.
        }


        foreach (string item in DirectoryFiles)
        {
            if (File.Exists("E/MyFolder/Log.txt"))// Check file exists.
            {
                Response.Write("File " + item + " Exists");
            }
         
        }
    }

No comments:
Write comments
Recommended Posts × +