2014-09-02 110 views
-3

所以这是我的蹩脚的代码如何从txt文件读取二维数组? C#

class begin 
    { 
     public static string[] Reader() 
     { 
      string[] theMap = System.IO.File.ReadAllLines(@"C:\Users\Public\Console Slayer\Map\map.txt"); 
      string[] Map = theMap.Clone() as string[]; 
      return Map; 
     } 
     public static void Printer() 
     { 
      foreach (string line in Reader()) 
      { 
       Console.WriteLine(line); 
      } 

     } 
     static void Main() 
     { 
      Reader(); 
      Printer(); 
     } 
    } 

我想使地图字符串转换成二维数组的功能使用。 我是新来编程,我知道我的代码是坏的。

+0

太棒了!你的问题是什么?说真的,我们没有*远程*足够的信息来帮助你。 – BradleyDotNET 2014-09-02 18:00:05

+0

如何将Map数组转换为二维数组 – nightxx 2014-09-02 18:00:58

+0

您可以提供更多关于您要完成的内容的信息吗?你的数据是什么样的,你为什么需要一个2D数组,它的结构应该是什么样子? – Jonesopolis 2014-09-02 18:01:10

回答

1

使用

Microsoft.VisualBasic.FileIO.TextFieldParser 

是的,这是一个VB组件,但它的作品尝试。没有必要重新发明轮子。样品用法:

OpenFileDialog od = new OpenFileDialog(); 
     od.Filter = "Tab delimited file (*.txt)|*.txt"; 
     if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 

      using (var reader = new Microsoft.VisualBasic.FileIO.TextFieldParser(od.FileName)) 
      { 
       reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited; 
       reader.Delimiters = new string[] { "\t" }; // the delimeter of the lines in your file 


       reader.ReadLine(); // skip header if needed, ignore titles 
       while (!reader.EndOfData) 
       { 
        try 
        { 
         var currentRow = reader.ReadFields(); // string array 
         // Include code here to handle the row. 
        } 

        catch (Microsoft.VisualBasic.FileIO.MalformedLineException vex) 
        { 

         MessageBox.Show("Line " + vex.Message + " is invalid. Skipping"); 
        } 
       } 
     } 
     } 
+0

您的尝试块没有右花括号。 – OMGtechy 2014-09-02 18:12:51