读取txt文件并添加到数组中的问题 [英] Problem with Reading txt files and adding into array
问题描述
你好我一直在研究一个涉及从几个文件夹中的几个txt文件中读取数据的项目。 txt文件主要包含数据,例如;
test.txt
1001 1200 1300 1400 1500
1400 7100 6500 8500 6000
5000 3000 4000 5000 2000
6000 2200 6333 0000 0000
...
我可以读取这个特定文件并将其分成数组,这样我就可以使用以下代码对每一列进行计算;
< pre lang =c#>列表< Double> List1 = new List< Double>();
列表< Double> List2 = new List< Double>();
.....
string path = @ H:\ test;
string searchPattern = * .txt 跨度>;
string [] filePaths = Directory.GetFiles(path,searchPattern,SearchOption.AllDirectories);
for ( int x = 0 ; x < filePaths.Length; x ++)
{
StreamReader file = new System.IO.StreamReader(filePaths [x]);
string line = file.ReadLine();
while ((line = file.ReadLine())!= null )
{
string [] data = line.Split(' ');
List1.Add(Convert.ToDouble(data [ 0 ]));
List2.Add(Convert.ToDouble(data [ 1 ]));
....
}
Double [] L1Array = List1.ToArray();
Double [] L2Array = List2.ToArray();
...
这部分代码效果非常好,能得到我想要的东西,但是当我尝试从不同的文件中获取数据,这些文件不仅仅是数字,而是具有与上述代码相同的字母;
test2.txt
姓名= Marc
姓氏=劳伦
性别=男性
...
ID = 123456789
我试图只将ID值(123466789)放入数组中我一直遇到错误;
mscorlib.dll中发生了'System.FormatException'类型的未处理异常
附加信息:字符串必须正好一个字符。
我也尝试更改代码如下;
StreamReader文件=新的System.IO。的StreamReader(文件路径[X]);
string line = file.ReadLine();
while((line = file.ReadLine())!= null)
{
char [] delimiters = new char [] {'\ r','\ n', '','='};
string [] data = line.Split(delimiters,StringSplitOptions.RemoveEmptyEntries);
我在c#中表现不是很好并且无法找到解决方法。
如果你能帮助我,我会很高兴。
谢谢不清楚为什么要使用这种原始数据格式...
但问题的解决方案很简单:只需准确编写代码即可。使用调试器和准确的方法。你的代码显示了许多与缺乏整洁有关的问题。
首先,你不处理你的 StreamReader实例
。这是正确的模式:
使用(StreamReader reader = new System.IO.StreamReader(filePaths [index])){
string line = reader.ReadLine();
// ...
} // reader.Dispose在这里自动调用
Hello I been working on a project that involves reading data from several txt files in several folders. The txt files contain data mostly numbers for example;
确保您了解所有类型实现接口 System.IDisposable
并确保通过使用调用
Dispose
code>声明(不要与使用
指令混淆)或不:
https://msdn.microsoft.com/en-us/library/system.idisposable%28v=vs.110 %29.aspx [ ^ ],
https:/ /msdn.microsoft.com/en-us/library/yh598w02.aspx [ ^ ]。
不要使用变量/类型/成员名称行< codex> x(我将其重命名为< code> ;索引。)使用语义敏感的名称,正确的英文拼写,没有缩写。
不要硬编码立即常量像字符串'\ r','\ n','','='。明确定义常量或< code>只读静态成员;在其他情况下,使用资源。
现在,如果你使用读取整个文件reader.ReadLine()
,你永远不需要'\ r','\ n'。只要知道你的文件是如何生成的,就可以使用精确的分隔符。
在
。再次,永远不要使用坏名称行 List1这样的行中有两大错误。新增(Convert.ToDouble(数据[0])); 击> List1
。不要硬编码0,1等。而是使用 string.Split
返回的数组中的元素数量并使用循环。最后,不要使用 Convert.ToDouble
。这就是它:解析,而不是转换。请理解解析可能成功或失败。相反,使用 double.TryParse
: https://msdn.microsoft.com/en-us/library/system.double.tryparse%28v=vs.110%29.aspx [ ^ ]。
依旧...
当你以一种干净的方式重写你的代码时,如果你还有任何关于运行时的问题,尝试使用调试器进行调试。无论如何,CodeProject对某些异常提出疑问而没有发现调试器下出现的问题没什么意义......
test.txt
1001 1200 1300 1400 1500
1400 7100 6500 8500 6000
5000 3000 4000 5000 2000
6000 2200 6333 0000 0000
...
I can read this particular file and divide it into arrays so I can do calculations for every single column with the following code;
List<Double> List1 = new List<Double>();
List<Double> List2 = new List<Double>();
.....
string path = @"H:\test";
string searchPattern = "*.txt";
string[] filePaths = Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories);
for (int x = 0; x < filePaths.Length; x++)
{
StreamReader file = new System.IO.StreamReader(filePaths[x]);
string line = file.ReadLine();
while ((line = file.ReadLine()) != null)
{
string[] data = line.Split(' ');
List1.Add(Convert.ToDouble(data[0]));
List2.Add(Convert.ToDouble(data[1]));
....
}
Double[] L1Array = List1.ToArray();
Double[] L2Array = List2.ToArray();
...
This part of code works very well and gets me what I want but when I try to get data from a different file that is not only digits but letters with the same code as above for example;
test2.txt
Name = Marc
Surname = Lauren
Gender = Male
...
ID = 123456789
where I been trying to get only ID value (123466789) into an Array I keep encountering the error;
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: String must be exactly one character long.
I also tried changing the code as following;
StreamReader file = new System.IO.StreamReader(filePaths[x]);
string line = file.ReadLine();
while ((line = file.ReadLine()) != null)
{
char[] delimiters = new char[] { '\r', '\n', ' ', '='};
string[] data = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
I am not very good in c# and couldn't find a way around it.
I would be Glad if you could help me out.
Thank youNot clear why would you use such primitive data format…
But the solution of the problem is simple: just write the code accurately. Use the debugger and accurate approaches. Your code shown many problems related to lack of neatness.
First, you don't dispose your instances of the StreamReader
. This is the correct pattern:
using (StreamReader reader = new System.IO.StreamReader(filePaths[index])) {
string line = reader.ReadLine();
//...
} // reader.Dispose is automatically called here
Makes sure you know all types implementing the interface System.IDisposable
and make sure you call Dispose
, via the using
statement (not to be confused with using
directive) or not:
https://msdn.microsoft.com/en-us/library/system.idisposable%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/yh598w02.aspx[^].
Don't use variable/type/member names line <codex>x (I renamed it to <code>index.) Use semantically sensitive names, in correct English spelling, without abbreviations.
Don't hard-code immediate constants like strings '\r', '\n', ' ', '='. Explicitly define constants or <code>readonly static members; in other cases, use the resources.
Now, if you read the whole file using reader.ReadLine()
, you never need '\r', '\n'. Just know how your file is generated and use exact delimiters which can be there.
Two big mistakes are in the lines like
. Again, never use bad names line List1.Add(Convert.ToDouble(data[0]));List1
. Don't hard-code 0, 1, etc. Instead, use the number of element in the array returned by string.Split
and use the loop. And finally, don't use Convert.ToDouble
. This is what it is: parsing, not "conversion". Please understand that parsing can be successful or failed. Instead, use double.TryParse
: https://msdn.microsoft.com/en-us/library/system.double.tryparse%28v=vs.110%29.aspx[^].
And so on…
When you rewrite your code in a neat way, if you still have any concerns about runtime, try to debug it using the debugger. Anyway, CodeProject questions on some exception without finding out what's going wrong under the debugger makes little sense…
这篇关于读取txt文件并添加到数组中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!