将多个文件读入一个字符串

Read multiple files onto a string

编辑:我忘了添加例外

我编写了这段代码,试图将多个文件读入一个字符串(稍后我可以拆分它们,每个文件的末尾都有一个单词,如分隔符)。

但是每次我尝试打开文件时,都会抛出一个异常: 附加信息:未将对象引用设置为对象的实例。

我尝试更改代码但没有成功。我是 C# 的新手,找不到我做错了什么。任何帮助将不胜感激。 PS:我正在使用一个单独的 class 来保存我的变量 - 因为我知道我将需要在代码的其他部分使用它们中的一些,所以我决定将它们设为全局变量。

谢谢

代码:

private void openPPFToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog open = new OpenFileDialog())
            {
                // Filter for PPF
                open.Filter = "PPF Files|*.PPF";
                open.Multiselect = true;
                open.Title = "Select a PPF File";
                if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
//Obtaining list of filenames
                    vars.fullFileName = new List<String>(open.FileNames);
                    vars.filepath = open.FileName;
                    foreach (string fileName in vars.fullFileName)
                    {
                        LoadedFiles.Items.Add(fileName.Substring(fileName.LastIndexOf(@"\") + 1));  
                    }
                    for(int i=0; i< vars.fullFileName.Count; i++)
                    {
                        using (var sr = new StreamReader(vars.filepath))
                        {
                            vars.files[i] = sr.ReadToEnd(); //I supposed that each string position could hold an entire file.
                        }
                        string teste1 = vars.files[3].ToString(); //Just trying to show the contents
                        textBox1.Text = teste1;
                    }


                }
            }
        }

Class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PPF_Converter_2._0
{
    class vars
    {
        public static List<String> fullFileName;
        public static string filepath;
        public static List<String> textdata;
        public static string sLine = "";
        public static string data;
        public static string[] files;


    }
}

您的数组 "files" 未初始化。你需要这样的东西:

Files = new string[3];

如果数组应该包含 3 个元素。

我认为你的文件读取有问题。

这样试试。

  foreach (String file in openFileDialog1.FileNames) 
    {
      string fileContent = File.ReadAllText(file);
     //do your activity here
    }