如何检查是否已添加或打开文本文件

时间:2018-03-07 08:51:03

标签: c#

我想打开并将文本文件内容添加到列表框中,但如果我想添加另一个文本文件,如何检查我添加的文件是否已添加到列表框中。我的意思是我不希望列表框重复。

private void openAndAddToolStripMenuItem_Click(object sender, EventArgs e)
{
    openFileDialog.Filter = "Text file|*.txt";
    openFileDialog.Title = "Open Text";
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        List<string> lines = new List<string>();
        using (StreamReader r = new StreamReader(openFileDialog.OpenFile()))

        {
            string line;
            while ((line = r.ReadLine()) != null)
            {
                donutListBox.Items.Add(line);
            }
        }
    }
} 

3 个答案:

答案 0 :(得分:4)

添加if:

if ( !donutListBox.Items.Contains(line) ){
    donutListBox.Items.Add(line);
}

答案 1 :(得分:1)

如果您使用.net framework 4+,则可以使用File.ReadAllLines(string filename)静态方法:

private void openAndAddToolStripMenuItem_Click(object sender, EventArgs e)
{
    openFileDialog.Filter = "Text file|*.txt";
    openFileDialog.Title = "Open Text";
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        var lines = File.ReadAllLines(openFileDialog.FileName);
        lines = lines.Where(line => !donutListBox.Items.Contains(line)).ToArray();
        donutListBox.Items.AddRange(lines);
    }
} 

答案 2 :(得分:0)

你可以试试

public static bool IsFileInUse(string filename)
{
  bool locked = false;
  try
  {
    FileStream fs =
    File.Open(filename, FileMode.OpenOrCreate,
    FileAccess.ReadWrite, FileShare.None);
    fs.Close();
  }
  catch (IOException ex)
  {
    locked = true;
  } 
 return locked;
}

并且:

if(!Class.IsFileInUse("FilePAth") && !donutListBox.Items.Contains(line))
{
     //your code
}