user1960368
user1960368

Reputation: 21

How to strip the full path using file info in C#

I am new to C# programming.Please suggest me how to retrieve the fullpath but using only file.Name in my code as I only want to enter file name in my listBox not full path

My code is:

listBox1.DataSource = GetFolder("..\\video\\");

private static List<string> GetFolder(string folder)
{
    List<string> FileList = new List<string>();

    var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg", 
                                                    SearchOption.AllDirectories)
    foreach (FileInfo file in allFiles)
    {
        FileList.Add(file.FullName);             
    }    

    return FileList;  
}

Upvotes: 1

Views: 5140

Answers (4)

Stephan Bauer
Stephan Bauer

Reputation: 9249

If I get you right, you want the FullPath as value but only the FileName displayed. To achieve this, you could use a List of FileInfos containing both of these values and tell the ListBox, which member is the value and which one should be displayed:

this.listBox1.DisplayMember = "Name";
this.listBox1.ValueMember = "FullName";
listBox1.DataSource = GetFolder("..\\video\\");

Player.URL = Convert.ToString(listBox1.SelectedValue);  // Instead of SelectedItem

private static List<FileInfo> GetFolder(string folder)
{
    List<FileInfo> fileList = new List<FileInfo>();

    foreach (FileInfo file in new DirectoryInfo(folder).GetFiles("*.mpg", SearchOption.AllDirectories))
    {
       fileList.Add(file); 
    }    

    return fileList;  
}

Upvotes: 1

Siva Charan
Siva Charan

Reputation: 18064

FileInfo(path).Directory.FullPath

Your actual problem of your code is missing semi-colon for this line

var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg", 
                                                    SearchOption.AllDirectories)

It should be

var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg", 
                                                    SearchOption.AllDirectories);

Upvotes: 1

Prasad
Prasad

Reputation: 154

  listBox1.DataSource = GetFolder("..\\video\\");

  private static List<string> GetFolder(string folder)
  {
        List<string> FileList = new List<string>();

        var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg", 
                                                SearchOption.AllDirectories)
        foreach (FileInfo file in allFiles)
        { 
              FileList.Add(file.Name);             
        }    

        return FileList;  
  }

Upvotes: 0

faheem khan
faheem khan

Reputation: 481

 FileList.Add(file.FullName);

Please Change this line like below

 FileList.Add(file.Name );

Upvotes: 0

Related Questions