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

C# 如何检查文本文件是否已添加或打开,c#,C#,我想打开一个文本文件并将其内容添加到列表框中,但如果我想添加另一个文本文件,如何检查我添加的文件是否已添加到列表框中。我的意思是我不希望列表框被复制 private void openAndAddToolStripMenuItem_Click(object sender, EventArgs e) { openFileDialog.Filter = "Text file|*.txt"; openFileDialog.Title = "Open Text"; if (ope

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

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);
            }
        }
    }
} 
private void openAndAddToolStripMenuItem\u单击(对象发送方,事件参数e)
{
openFileDialog.Filter=“文本文件|*.txt”;
openFileDialog.Title=“打开文本”;
if(openFileDialog.ShowDialog()==DialogResult.OK)
{
列表行=新列表();
使用(StreamReader r=newstreamreader(openFileDialog.OpenFile()))
{
弦线;
而((line=r.ReadLine())!=null)
{
donutListBox.Items.Add(行);
}
}
}
} 
添加一个if:

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

如果您使用.net framework 4+,则可以使用
File.ReadAllLines(字符串文件名)
static方法:

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);
    }
} 
你可以试试

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
}

@HungNguyen所以请不要忘记接受答案。除了检查列表框中是否有重复项之外,如果您想知道您之前已经打开了该文件以提取值,您可以维护访问文件的集合。