天天看点

文件操作

/// <summary>

        /// 将存贮在文本文件中的数据绑定到DropDownList中  test,test

        /// </summary>

        /// <param name="drdlst">下拉菜单</param>

        /// <param name="filePath">虚拟路径</param>

        public void Drdlst_BindDataByTxt1(DropDownList drdlst, string filePath)

        {

            string fileName = HttpContext.Current.Server.MapPath(filePath);

            string content = "";

            StreamReader sr = null;

            try

            {

                //打开文件并显示其内容

                sr = new StreamReader(fileName, System.Text.Encoding.Default);

                for (string line = sr.ReadLine(); line != null; line = sr.ReadLine())

                {

                    content += line.ToString();

                }

                string[] arr = content.Split(',');

                for (int i = 0; i < arr.Length; i++)

                    ListItem li = new ListItem();

                    li.Text = arr[i].ToString();

                    li.Value = arr[i].ToString();

                    drdlst.Items.Add(li);

            }

            catch (IOException ee)

                HttpContext.Current.Response.Write("<script>alert(" + ee.Message + ")</script>");

            finally

                if (sr != null)

                    sr.Close();

        }

        /// <summary>

        /// 获取txt中信息

        /// <returns></returns>

        public string GetTxtInfo(string filePath)

            string str = "";

                    str += line.ToString();

            return str;

        /// 保存数据到txt中

        /// <param name="str">要保存的数据</param>

        public void SaveTxtInfo(string str, string filePath)

            StreamWriter sw = null;

            FileStream oFileStream = null;

                if (!System.IO.File.Exists(fileName))

                    oFileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);

                else

                    oFileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);

                sw = new StreamWriter(oFileStream, Encoding.Default);

                sw.Write(str);

                sw.WriteLine();

                if (sw != null)

                    sw.Close();

                    oFileStream.Close();