在 C# 中给出文件的路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10083651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Giving path of a file in C#
提问by Sarao
I want to open a xxx.txt file kept on desktopof my Computer but the program gives an
我想打开一个保存在我电脑桌面上的xxx.txt 文件,但程序给出了一个
error Parser error unrecognized escape sequence '\D'. I am trying to give the path of the
错误解析器错误无法识别的转义序列 '\D'。我试图给出路径
file as "C:\Documents and Settings\user\Desktop\xxx.txt".
文件为“C:\Documents and Settings\user\Desktop\xxx.txt”。
Am i giving the path in a right way or is there any other way to give it
我是在以正确的方式给出路径还是有其他方法可以给出路径
采纳答案by Anders Abel
\is an escape character in C# strings. It is used for special characters, such as line break (\n). To write a literal \you have to quote with another \:
\是 C# 字符串中的转义字符。它用于特殊字符,例如换行符 ( \n)。要写一个文字,\你必须引用另一个\:
string myFileName = "C:\Documents and Settings\user\Desktop\xxx.txt";
An alternative is to disable quoting for the string with the @character:
另一种方法是禁用带有@字符的字符串的引用:
string myFileName = @"C:\Documents and Settings\user\Desktop\xxx.txt";
回答by llj098
Change your path to C:\\Documents and Settings\\user\\Desktop\\xxx.txt.
将您的路径更改为C:\\Documents and Settings\\user\\Desktop\\xxx.txt.
回答by ionden
Use this path:
使用此路径:
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "xxx.txt");
回答by las
Try to use C:\Documents and Settings\user\Desktop/xxx.txt
尝试使用C:\Documents and Settings\user\Desktop/xxx.txt
Instead of C:\Documents and Settings\user\Desktop\xxx.txt
而不是 C:\Documents and Settings\user\Desktop\xxx.txt
回答by Sabeen
I had to access a file in my project, so the folder 'lib' which contains all the files i need, i placed this folder in the 'bin' folder of my project, and now i can access any file i need from lib folder. In code path i used is as follows:
我必须访问我项目中的一个文件,因此包含我需要的所有文件的文件夹“lib”,我将此文件夹放在我项目的“bin”文件夹中,现在我可以从 lib 文件夹访问我需要的任何文件. 在我使用的代码路径中,如下所示:
StreamReader sr = new StreamReader("..\lib\myFile.src");
Works well! :)
效果很好!:)

