Search code examples
c#winformsopenfiledialog

How to show the full path and filename in OpenFileDialog


I'm using openfiledialog to open the file calender.txt, when it opens it displays calender as the filename and .txt in the filter box without the directory c:\

Can anyone please show me how to code the dialog so that i get C:\calender in the dialog

private void openFileButton_Click(object sender, EventArgs e)
{
     OpenFileDialog ofd = new OpenFileDialog();
     ofd.InitialDirectory = (@"C:\");
     ofd.Filter = ("*.txt| Text File");
     ofd.FileName = "calender.txt";
     ofd.CheckFileExists = false;

     if (ofd.ShowDialog() == DialogResult.OK)
     {
        if (CheckValidity(ofd.FileName))
        {
            try
            {
                streamWriter sw = new streamWriter(ofd.FileName);
            }
            catch (FileLoadException flEx)
            {
                MessageBox.Show(flEx.Message);
            }
            else
            {
            }
        }
    }
}

Solution

  • Can set the file name to be whatever you like in the dialog. If you want to show the full path at the start, you can do the following:

    OpenFileDialog ofd = new OpenFileDialog();
    ofd.InitialDirectory = (@"C:\");
    ofd.FileName = Path.Combine(ofd.InitialDirectory, "calendar.txt");
    

    Keep in mind that this won't stay like this once a user selects a different file, but it won't actually matter to you because once they hit Open, FileName will have the full path for you.