将文件名添加到.txt文件时出现问题 [英] Problem in adding file names to .txt file
本文介绍了将文件名添加到.txt文件时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试将文件名添加到列表时,我得到错误(对象引用没有设置为对象的实例)
button1_click
---用于获取textbox1的文件夹路径
button2_click
---用于存储文件名到列表
button3_click
---用于将文件名保存到report.txt
I,m getting error(object reference not set to an instance of an object) when i try to add file names to list
button1_click
--- for getting the folder path to textbox1
button2_click
--- for storing filenames to list
button3_click
--- for saving filenames to report.txt
public partial class Form1 : Form
{
List<string> fileStore = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button2_Click(object sender, EventArgs e)
{
DirectoryInfo dir1 = new DirectoryInfo(textbox1.text);
FileInfo[] files = dir1.GetFiles("*.*", SearchOption.AllDirectories);
try
{
foreach (FileInfo f in files)
{
fileStore.Add(f.Name.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
const string sPath = "report.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach (string item in fileStore)
{
SaveFile.WriteLine(item.ToString());
}
SaveFile.Close();
MessageBox.Show("Programs saved!");
}
}
紧急情况已删除。
更正了格式和/或语法问题。
[/ Edit]
推荐答案
可能你需要像这样初始化你的fileStore变量:
Probably you need to initialize your "fileStore" variable like this :
List<string> fileStore = new List<string>();
这篇关于将文件名添加到.txt文件时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文