Find files in the startup directory in C#

[find files]

In some programs you may want to find files that were installed with the program. One way to do that is to put the files in the program’s installation directory. Open the Project menu, select Add Existing Item, find the file, and click Add. Then select the file in Project Explorer and use the Properties window to set its “Copy to Output Directory” property to “Copy if newer.” Now when you build the project, the file is copied into the output directory whenever necessary.

When you install the project, be sure you include the file, too.

This example uses the following code to find the file Greeting.rtf in the startup directory when it starts.

private void Form1_Load(object sender, EventArgs e)
{
    string filename = Path.Combine(
        Application.StartupPath, "Greeting.rtf");
    rchGreeting.LoadFile(filename);
}

The program uses the System.IO.Path.Combine method to add the file name Greeting.rtf to the startup path. The Combine method adds a \ between the two pieces of the path if necessary so you don’t need to worry about whether the startup path includes a trailing \. After composing the file’s full name, the program simply loads it into its RichTextBox control.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in directories, files and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *