c#实现写入,读取实现百度搜索框

来源:互联网 发布:360软件开放 编辑:程序博客网 时间:2024/05/18 07:19

        //写入内容
        private void write(TextBox textBox)
        {
            if (!File.Exists(path))
            {
                FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write("\r\n" + textBox.Text);
                sw.Flush();
                sw.Close();
                fs.Close();
            }
            else
            {
                FileStream fs = new FileStream(path ,FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write("\r\n" + textBox.Text);
                sw.Flush();
                sw.Close();
                fs.Close();
            }

        }
        string[] s = new string[] { };
        //绑定文本
        public void bindTxt(TextBox textBox)
        {
            List<string> a = s.ToList();
            StreamReader sr = new StreamReader(path, Encoding.UTF8);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                a.Add(line);
            }
            s = a.ToArray();
            var source = new AutoCompleteStringCollection();
            source.AddRange(s);
            textBox.AutoCompleteCustomSource = source;
            textBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            textBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
            sr.Close();

        }


private void button1_Click_1(object sender, EventArgs e)
        {
            if (!File.Exists(path))
            {
                write(textBox1);
            }
            else
            {
                StreamReader sr = new StreamReader(path, Encoding.UTF8);
                bool isWirte = true;
                string line1;

                while ((line1 = sr.ReadLine()) != null)
                {
                    if (line1 == textBox1.Text)
                    {
                        isWirte = false;
                        sr.Close();
                        break;
                    }
                }
                if (isWirte)
                {
                    sr.Close();
                    write(textBox1);
                }
                sr.Close();
                bindTxt(textBox1);
            }
        }

    }
}



0 0