Find a file in the program's startup directory in C#

In some programs you may want to find a file that was installed with the program. One way to do that is to put the file in the program's installation directory. Open the Project menu, select Add Existing Item, find the file, and click Add. Now 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. 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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.