将文本文件从资源转换为数组 [英] Convert A Text File From Resources Into Array
问题描述
我需要读取我上传到 Resources 文件夹中的 txt 文件,然后我必须将其转换为 string[] 数组.无论如何,当我调试代码时,在第二行我得到以下异常: System.ArgumentException: 'Illegal characters in path'.
I need to read a txt file I uploaded in Resources folder and then I have to convert it into an a string[] array. Anyway, when I debug the code, at the second line I get the following exception: System.ArgumentException: 'Illegal characters in path'.
我已经用我电脑上的一个文件尝试了这个方法,它有效.我检查了我的文本中的特殊字符,但我没有找到任何东西.我删除了一行开头的空格.
I've tried this method with a file from my computer and it works. I checked my text for special characters but I havent'found anything. I removed space at the beginning of a line.
string text = Convert.ToString(Resources.File);
string[] lines = File.ReadAllLines(text).ToArray();
尝试使用来自计算机的文件:它有效.
Try with file from computer: it works.
string text = Convert.ToString(@"C: \File.txt");
if (File.Exists(text))
{
string[] lines = File.ReadAllLines(text);
int i = 1;
if (lines[i] == abc.Text)
{
DO STUFF;
f2.ShowDialog();
}
}
我除了要转换的文件.
推荐答案
当您将 .txt
文件添加到 .resx
资源时,设计器将创建一个字符串财产.
When you add a .txt
file to a .resx
resource, the designer will create a string property for that.
假设属性名称是 MyFile
,那么要获取行,您只需要使用 Environment.NewLine
拆分字符串:
Assuming the property name is MyFile
, then to get the lines you just need to split the string using Environment.NewLine
:
var lines = Properties.Resources.MyFile
.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
注意:如果出于任何原因,您对 .txt
文件的 byte[]
感兴趣,您可以设置资源设计器中的文件类型为二进制:
Note: If for any reason, you are interested to have the byte[]
for a .txt
file, you can set the file type in resource designer to binary:
这篇关于将文本文件从资源转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!