C#中的特殊Filespec字符 [英] Peculiar Filespec character in C#

查看:106
本文介绍了C#中的特殊Filespec字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今晚在布置一个程序来打开和解析文件时,我遇到了从未见过的东西.在我用于学习示例的文本中,语句中的所有文件规范均以@开头,后跟实际的文件路径.这本书没有解释,索引中缺少该字符.我检查了来自Microsoft的示例,其中也出现了神秘的@符号,也没有进行解释.

我已经用很多语言编程过,但是我以前从未见过.这是为了什么?仅使用字符串有什么问题?

今晚我看过的所有示例都使用硬编码的文件名(例如"C:\ Target \ MyFile.txt"),但是我使用的是通过OpenFileDialog获取的字符串变量.为了正确引用文件,我是否还需要在变量前添加"@"符号?这适用于所有.Net语言还是仅适用于C#?

通常,我会花一些时间以几种不同的方式编写代码,直到它起作用为止,但是时间太晚了,我睡眠不足,我真的很想明天晚上取得一些认真的进步.下班以后.我会很高兴地解释此字符的使用以及为什么/何时需要此字符.这样可以为我节省许多我没有的时间. :)

Tonight while laying out a program to open and parse a file I came across something I''ve never seen before. In the text I''m using for learning examples, all of the file specs in statements begin with @ followed by the actual file path. The book doesn''t explain it, and the character is missing from the index. I checked examples from Microsoft, and the mysterious @ symbol is there, as well, also without explanation.

I''ve programmed in a lot of languages, but I''ve never seen this before. What''s it for? What''s wrong with using just a string?

All the examples I''ve looked at tonight use a hard-coded filename (e.g. "C:\Target\MyFile.txt"), but I''m using a string variable acquired by using an OpenFileDialog. Do I still need to prepend the ''@'' symbol to my variable in order to reference the file properly? Does this apply to all .Net languages, or just C#?

Ordinarily I''d just spend the hours required to write the code several different ways until it works, but it''s late and I''m short of sleep, and I''d really like to make some serious progress tomorrow night after work. I''d appreciate an explanation of the use of this character, and why/when it''s required. That would save me many hours I don''t have available. :)

推荐答案

@引号的优点是转义序列不被处理,因此编写起来很容易.
例如,我不能在字符串中使用\,因为它是一个转义序列.
因此,我需要使用\\,这实际上意味着C#中的单个"\"(编译时).

相反,我可以使用@操作.

string strPath = @"C:\Docs\Source\a.txt";而不是strPath = "c:\\Docs\\Source\\a.txt";.
The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write.

As an example, I cannot use \ in my string as it is an escape sequence.
So I need to use a \\ which essentially means a single "\" in C# (when compiled).

Instead I could use the @ operation.

string strPath = @"C:\Docs\Source\a.txt"; rather than strPath = "c:\\Docs\\Source\\a.txt";.


这篇关于C#中的特殊Filespec字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆