how to get filename using c#


  • the below is the sample that i get from the internet, one thing that i can't find
    on the net is that ..if let say i don't want to just hardcode the fileName like sample
    below..what command should i use in c# to read and get the file path automatically
    without hardcode the filename? the reason is because i want to write a ftp program
    using c# to upload file to ftp server, so i want the program to automatic get the
    file from the drive and upload, that is why i can't hardcode the filename in
    program, appreciate if u have sample sourcecode on this, thx

    fileName = @"C:\mypath\myfile.txt" ;
    string path = @"C:\mypath\" ;
    string result;

    result = Path.GetFileName(fileName);

    Friday, March 04, 2011 1:30 AM


  • you can use Directory class to get the files

    string[] files = Directory.GetFiles(path);

    it will return all files under your path. and to get the files name

    foreach(var file in files)

    filename = Path.GetFileName(file);


    My sugesstion if your requirment is to upload a file automatically,

    1. you can write a service scheduler to check directory, then upload the files to the ftp server,

    2. you can use the FileSystemWatcher class under System.IO.  This class will cath any changes of your files and fire an event based on those changes (in your case, you can implement your upload method when a file was created, updated, or changed)


    Hope this help.

    Regards, Christofel
    • Proposed as answer by Mio_Miao Monday, March 14, 2011 4:11 AM
    • Marked as answer by Mio_Miao Wednesday, March 16, 2011 5:06 AM
    Friday, March 04, 2011 2:07 AM