Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 列表框不显示添加到winforms文件夹中的文件_C# - Fatal编程技术网

C# 列表框不显示添加到winforms文件夹中的文件

C# 列表框不显示添加到winforms文件夹中的文件,c#,C#,我试图显示已添加到特定文件夹的文件,然后将其显示在列表框中 这是我的代码: public partial class Form1 : Form { public Form1() { InitializeComponent(); string path = @"C:\Database"; MonitorDirectory(path); } private void listBox1_SelectedIndexChan

我试图显示已添加到特定文件夹的文件,然后将其显示在
列表框中

这是我的代码:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        string path = @"C:\Database";
        MonitorDirectory(path);
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    private static void MonitorDirectory(string path)
    {
        FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
        fileSystemWatcher.Path = path;
        fileSystemWatcher.Created += FileSystemWatcher_Created;
        fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;
        fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;
        fileSystemWatcher.EnableRaisingEvents = true;
    }

    private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
    {
        string path = @"C:\Database";
        ListBox listBox1 = new ListBox();
        listBox1.Items.Add(String.Format(path));
    }

}
我的列表框名为
listBox1

我不希望它在控制台应用程序中运行,而是在winform中运行


谢谢您正在创建一个新的列表框。我认为您应该使用您在UI中拥有的一个,而不是创建它(或者,如果您创建了它,则必须将其放入UI思想代码中)


在Form1的构造函数上移动Listbox1声明该代码将始终向在该方法中创建并在代码退出该方法时自动销毁的列表框中添加相同的字符串“C:\database”,而不添加任何文件,好吗?那么,当一个文件添加到该文件夹中时,我可以让它在列表框中显示新文件吗?
ListBox listBox1 = new ListBox(); // remove this line of code and put a list item in UI and name it listBox1