locked
get file name RRS feed

  • Question

  •  

    Hi all,

    I am very new to C#.

    I have a folder containing files that need to be attached in a table.  I would like to get the file name of the files under the folder.  is there anyway to do that?

     

    e.g.,

     

    C:\FilePath\FileName1.jpeg

    C:\FilePath\FileName2.jpeg

    C:\FilePath\FileName3.jpeg

    C:\FilePath\FileName4.jpeg

     

    Thanks in advance!

    Tuesday, October 9, 2007 5:04 AM

Answers

  • Of course there is.

    DirectoryInfo or Directory class can be used to get FileInfo objects. Those classes have a method called GetFiles, which returns all files you have in that directory, or you can add a search pattern. For example "*.jpeg". The return value is an array of FileInfo objects. FileInfo has a property called FullName, which contains the full file name with path.

    Difference between Directory and DrectoryInfo is that Directory is a static class, and DirectoryInfo represents the folder as an object, and must be instantiated.

    FileInfo[] files = Directory.GetFiles(@"C:\MyFiles\", "*.jpeg");
    foreach(FileInfo file in files)
    {
        Console.WriteLine(file.FullName);
    }
    Tuesday, October 9, 2007 6:32 AM

All replies

  • Of course there is.

    DirectoryInfo or Directory class can be used to get FileInfo objects. Those classes have a method called GetFiles, which returns all files you have in that directory, or you can add a search pattern. For example "*.jpeg". The return value is an array of FileInfo objects. FileInfo has a property called FullName, which contains the full file name with path.

    Difference between Directory and DrectoryInfo is that Directory is a static class, and DirectoryInfo represents the folder as an object, and must be instantiated.

    FileInfo[] files = Directory.GetFiles(@"C:\MyFiles\", "*.jpeg");
    foreach(FileInfo file in files)
    {
        Console.WriteLine(file.FullName);
    }
    Tuesday, October 9, 2007 6:32 AM
  • Thanks for your reply, it works!.

     

    I also figured out on how to do it using sql statement:

     

    Code Block

    drop table #DIR

    CREATE TABLE #DIR (FileName varchar(100))

    DECLARE @Path varchar(200)

    SET @Path = 'C:\Path\'

    DECLARE @Cmd varchar(1050)

    SET @Cmd = @Path + ' /b'

     

    INSERT INTO #DIR

    EXEC master..xp_CmdShell @Cmd

     

    SELECT * FROM #DIR

     

     

    Thanks!
    Tuesday, October 9, 2007 11:50 PM