John Smith
John Smith

Reputation: 3

using relative path to open excel file in visual studio using c#

I seem to be having a problem opening an excel file with a relative path in visual studio. The file is being saved to:

C:\Users\UserName\Documents\Filename.xls

on any machine. I have tried using:

Process.Start(@"~\Documents\Filename.xls");

to open the excel file, but it throws an error saying the file location cannot be found. Is there something I am doing wrong? Thank you in advance.

Upvotes: 0

Views: 936

Answers (3)

dsdel
dsdel

Reputation: 1062

'~' is not a valid path identifier in Windows (It does refer to the home directory on *nix). I am not sure what you are trying to achieve, but perhaps you want SpecialFolder see description here at MSDN?

var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

Will return: C:\Users\'UserName'\Documents\

Upvotes: 0

Werner
Werner

Reputation: 281

You could use combine to get the full path

var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullPath.Combine(folderPath, "filename.xls");
Process.Start(fullPath);

If you know the relative path to the working folder use

var fullPath = Path.GetFullPath(relPath);

Upvotes: 0

Edwin Bentveld
Edwin Bentveld

Reputation: 101

The '~' character is used in Linux.

With the following code you can obtain the path for special folders:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) 

The MyDocuments can be replaced for other Windows specific folder like:

  • UserProfile
  • MyPictures
  • Desktop

Upvotes: 3

Related Questions