简体   繁体   English

使用相对路径使用C#在Visual Studio中打开Excel文件

[英]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. 我似乎在Visual Studio中使用相对路径打开excel文件时遇到问题。 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. 打开excel文件,但抛出错误,提示找不到文件位置。 Is there something I am doing wrong? 我做错什么了吗? Thank you in advance. 先感谢您。

The '~' character is used in Linux. 在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: MyDocuments可以替换为其他Windows特定文件夹,例如:

  • UserProfile 用户资料
  • MyPictures 我的照片
  • Desktop 桌面

'~' is not a valid path identifier in Windows (It does refer to the home directory on *nix). “〜”在Windows中不是有效的路径标识符(它确实引用* nix上的主目录)。 I am not sure what you are trying to achieve, but perhaps you want SpecialFolder see description here at MSDN ? 我不确定您要实现的目标,但是也许您想让SpecialFolder 在MSDN上查看说明

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

Will return: C:\\Users\\'UserName'\\Documents\\ 将返回:C:\\ Users \\'UserName'\\ Documents \\

You could use combine to get the full path 您可以使用Combine获得完整路径

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM