C# - 我在从Listbox中覆盖文本文件中的数据时遇到问题

时间:2018-03-20 18:50:18

标签: c# winforms listbox

我正在创建一个小程序,可以将网站网址/链接保存到列表框中。从那里,我可以将列表框的内容保存到文本文件中。然后将该文本文件保存到桌面上过早为该程序制作的文件夹中。应用程序可以打开文本文件并将内容显示到列表框,以及创建和保存新的文本文件。我的问题是如何正确覆盖文本文件。

这是我保存工具箱按钮的代码:

jQuery(document).ready(function($){
$("#fld_7213314_3_file_list").change(function(){
alert("The text has been changed.");
if ( $('#fld_7213314_3_file_list').children().length > 0 ) {
 alert("had file uploaded")
}
});
});

问题是在使用“另存为工具栏”按钮创建文本文件后,编译器似乎忽略了我的if语句中的代码,并假设我想要始终创建要保存的新文本文件。提前谢谢!

1 个答案:

答案 0 :(得分:0)

经过多次修改和外界帮助后,我发现了问题所在。我试图从我的文件夹目录中检索的文件名为null,因此不会保存任何内容。因此我所做的是如果上次打开/保存到表单上,我会从表单中检索文件名。

Here's a picture to help visualize. Any text file that was last opened or saved, it would display it here and compiler would use that path in my code.

使用文件的完整路径而不是缩短文件的路径,我会将文件的内容覆盖到该路径。这样做还允许我将文件保存在计算机上的任何位置。

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
            {            
                var fileNameAndPath = filedisplaylabel.Text; 

        if (string.IsNullOrEmpty((fileNameAndPath)))
        {
            OpenFileDialog openfiledialog1 = new OpenFileDialog();

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                filedisplaylabel.Text = Path.GetFullPath(openFileDialog1.FileName); 
                fileNameAndPath = filedisplaylabel.Text;
            }
        }                        
            try
            {
                using (FileStream fstream = new FileStream(fileNameAndPath,
                    FileMode.Open,
                        FileAccess.Write))
                {
                    using (StreamWriter write = new StreamWriter(fstream))
                    {
                        foreach (var item in WebListBox.Items)
                            write.WriteLine(item.ToString());
                        write.Close();
                    }
                    fstream.Close();
                }
            }
            catch (DirectoryNotFoundException ex)
            {
                MessageBox.Show(ex.Message, "File not found error");
            }                                                                                 
    }
相关问题