Hi Guys,
I am trying to display a selected file name by user(using OpenFileDialog class and FileName property) as

if (dlgOpen.ShowDialog() == DialogResult.OK)
    {
     txtFileName.Text = dlgOpen.FileName;
    }

but the problem is this return all path info which I do not need! Can you please let me know How I can get rid of the path and just retrieve or display the file name only

Thanks for your time, in advanced.

Dani AI

Generated

Both and gave the right directions: the dialog API can hand you just the file name, and the System.IO helpers let you extract a name from any full path. Which to use depends on context—if you already have an OpenFileDialog instance prefer the dialog’s filename-only property; if you only have a string path (or are using a different dialog API), use System.IO to parse it.

Extra tips not shown above:

  • In WinForms OpenFileDialog there are both singular and plural helpers: use the plural when Multiselect is enabled so you can process every chosen file. In WPF (Microsoft.Win32.OpenFileDialog) the filename-only convenience property is not available, so fall back to System.IO parsing.
  • To get the name without the extension use the Path method that strips extensions, or inspect FileInfo.Extension and FileInfo.Name depending on whether you prefer object semantics.
  • Always check the dialog result before using files and handle an empty selection gracefully (the FileNames array can be empty if the user cancels).

Example pattern for multiselect (map full paths to base names):

using System.IO;
using System.Linq;

string[] selected = openDialog.FileNames; // may be empty
string[] baseNames = selected.Select(p => new FileInfo(p).Name).ToArray();
txtFileName.Text = string.Join(", ", baseNames);

For reference on the parsing helpers see the docs for Path.GetFileNameWithoutExtension and FileInfo.Name (Path.GetFileNameWithoutExtension, FileInfo.Name).

Recommended Answers

All 3 Replies

Try this...

if (dlgOpen.ShowDialog() == DialogResult.OK)

    {

     txtFileName.Text = dlgOpen.SafeFilename;

    }

...or Path.GetFileName();

using System;
using System.IO;

namespace DW_398724
{
   class Program
   {
      static void Main(string[] args)
      {
         string strFilepath = "c:/documents and settings/user/directory/sub_director/text.txt";
         Console.Write(Path.GetFileName(strFilepath)); // prints text.txt
      }
   }
}

Thank you both bhagawatshinde and thines01,
it works now

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.