c#读写建立临时文件

    class Temp
        {
            /// <summary>
            /// 写临时文件
            /// </summary>
            /// <param name="user">要写入文件的内容 不带后缀</param>
            /// <param name="password">要写入的内容</param>
            public void WriteTemp(string user,string password)
            {
                string mypath;      //保存路径
                //得到当程序的路径
                int i = Application.ExecutablePath.LastIndexOf (@"\");
                //得到要保存文件的位置
                mypath = Application.ExecutablePath.Substring(0,i);
                FileInfo myfile = new FileInfo(mypath +@"\"+ user + ".tmp");
                //判断文件是否存在
                if (!myfile.Exists)
                {
                    //文件不存在建立一个文件
                    myfile.Create();
                }
                FileStream mystream = new FileStream(myfile.ToString() ,FileMode.Open);
                StreamWriter mywriter = new StreamWriter(mystream,Encoding.Unicode );
                //写入数据
                mywriter.WriteLine(password);
                mywriter.Flush();
                mywriter.Close();
            }

             /// <summary>
            /// 要读的临时文件
            /// </summary>
            /// <param name="user">要读的文件名</param>
            /// <returns>返回文件的内容</returns>
            public string ReadTemp(string user)
            {
                string mypath;      //保存路径
                string context;     //保存文件的内容
                //得到当程序的路径
                int i = Application.ExecutablePath.LastIndexOf(@"\");
                //得到要保存文件的位置
                mypath = Application.ExecutablePath.Substring(0, i);
                FileInfo myfile = new FileInfo(mypath + @"\" + user + ".tmp");
                //判断文件是否存在
                if (!myfile.Exists)
                {
                    //提示用户文件不存在建立一个文件
                    MessageBox.Show("文件不存在", "提示");
                    return  context =null;
                }
                else
                {
                    //文件存在时
                    FileStream mystream = new FileStream(myfile.ToString(), FileMode.Open);
                    StreamReader myread=new StreamReader (mystream );
                    //得到文件的内容
                    context= myread.ReadToEnd();
                    myread.Close();
                }
                return context;
            }
        }

posted @ 2010-03-23 19:37  三月软件工作室——任忌  阅读(2150)  评论(0编辑  收藏  举报