+ -
当前位置:首页 → 问答吧 → 读txt时出现问题(不报错,文件显示不出来)

读txt时出现问题(不报错,文件显示不出来)

时间:2011-12-16

来源:互联网

try
  {
  Dictionary<string, string> dic = new Dictionary<string, string>();
  string[] str = File.ReadAllLines("英汉词典.txt", Encoding.Default);
  foreach (string line in str)
  {
  string[] lines = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);//移除所有空白字符
  if (line.Length == 2)
  {
  if (!dic.ContainsKey(lines[0]))//如果key中有相同的值将不添加进key
  {
  dic.Add(lines[0], lines[1]); }
  }
  }
  foreach (string s in dic.Values )
  {
  Console.WriteLine(s);
  }
  Console.WriteLine("哈哈");
  }
  catch (Exception ex)
  {
  Console.WriteLine(ex.Message );
  }
  Console.ReadLine();
“英汉词典.txt”文件在Debug文件夹下

作者: heip4965   发布时间: 2011-12-16

string[] str = File.ReadAllLines("英汉词典.txt", Encoding.Default);

此处打断点,单步调式一下,看STR内是否有数据

作者: q107770540   发布时间: 2011-12-16

没有数据

作者: heip4965   发布时间: 2011-12-16

显示不出来就是dic是空的


所以 string[] lines = line.Split(new char[] { ' ' }, 这个可能是空的

或者没有满足下面条件的数据,自己打个断点分析一下就知道了
StringSplitOptions.RemoveEmptyEntries);
  if (line.Length == 2)
  {
  if (!dic.ContainsKey(lines[0]))//如果key中有相同的值将不添加进key

作者: xiongxyt2   发布时间: 2011-12-16

C# code

using System;
using System.IO;
using System.Text;
 
class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
 
        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            string[] createText = { "Hello", "And", "Welcome" };
            File.WriteAllLines(path, createText, Encoding.UTF8);
        }
 
        // This text is always added, making the file longer over time
        // if it is not deleted.
        string appendText = "This is extra text" + Environment.NewLine;
        File.AppendAllText(path, appendText, Encoding.UTF8);
 
        // Open the file to read from.
        string[] readText = File.ReadAllLines(path, Encoding.UTF8);
        foreach (string s in readText)
        {
            Console.WriteLine(s);
        }
    }
}


作者: xiongxyt2   发布时间: 2011-12-16