方式一:用FileStream
-
- SaveFileDialog sf = new SaveFileDialog();
-
- sf.Filter = "txt文件|*.txt|所有文件|*.*";
-
- sf.AddExtension = true;
-
- sf.Title = "写文件";
-
- if(sf.ShowDialog()==DialogResult.OK)
- {
-
- FileStream fs = new FileStream(sf.FileName,FileMode.Create);
-
- byte [] data =new UTF8Encoding().GetBytes(this.textBox1.Text);
-
- fs.Write(data,0,data.Length);
-
- fs.Flush();
- fs.Close();
- }
方式二:用StreamWriter
-
- SaveFileDialog sf = new SaveFileDialog();
-
- sf.Filter = "txt文件|*.txt|所有文件|*.*";
-
- sf.AddExtension = true;
-
- sf.Title = "写文件";
-
- if (sf.ShowDialog() == DialogResult.OK)
- {
-
- FileStream fs = new FileStream(sf.FileName, FileMode.Create);
-
- StreamWriter sw = new StreamWriter(fs);
-
- sw.Write(this.textBox1.Text);
-
- sw.Flush();
-
- sw.Close();
- fs.Close();
- }
- string FileName = Guid.NewGuid().ToString() + ".txt";
- StringBuilder ckpw = new StringBuilder("\"凭证输出\", \"V800\", \"001\", \"东风随州专用汽车有限公司\"," + "\"F89自由项16\", \"F90审核日期:\"");
- if (!FileIO.IsFolderExists(Server.MapPath("pzsc")))
- FileIO.CreaterFolder(Server.MapPath(""), "file://pzsc/");
- string filePath = Server.MapPath("pzsc") + "\\" + FileName;
- System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, false, Encoding.GetEncoding("GB2312"));
- sw.WriteLine(ckpw.ToString());
- sw.Close();
方式三:用BinaryWriter
-
- SaveFileDialog sf = new SaveFileDialog();
-
- sf.Filter = "txt文件|*.txt|所有文件|*.*";
-
- sf.AddExtension = true;
-
- sf.Title = "写文件";
-
- if (sf.ShowDialog() == DialogResult.OK)
- {
-
- FileStream fs = new FileStream(sf.FileName, FileMode.Create);
-
- BinaryWriter bw = new BinaryWriter(fs);
- bw.Write(this.textBox1.Text);
-
- bw.Flush();
-
- bw.Close();
- fs.Close();
- }
C#缓存流示例------>用缓存流复制文件
C#文件处理操作必须先导入命名空间:using System.IO;
背景:使用VS2005、一个按钮、一个窗体、C#缓存流、把D:\KuGoo\爱得太多.wma复制到D:\并更名为love.wma,即:D:\love.wma
在按钮的Click事件中添加如下代码:
- private void button1_Click(object sender, EventArgs e)
- {
-
- FileStream fs = new FileStream(@"D:\KuGoo\爱得太多.wma",FileMode.Open);
- FileStream fs2 = new FileStream(@"D:\love.wma",FileMode.Create);
-
-
-
-
- byte[] data = new byte[1024];
-
- BufferedStream bs = new BufferedStream(fs);
- BufferedStream bs2= new BufferedStream(fs2);
-
-
-
- while(fs.Read(data,0,data.Length)>0)
- {
- fs2.Write(data,0,data.Length);
- fs2.Flush();
- }
-
- fs.Close();
- fs2.Close();
- }
C#内存流示例----->用内存流来读取图片
C#文件处理操作必须先导入命名空间:using
System.IO;
背景:一个窗体、一个pictureBox、一个lable[没有选择图片,lable的text为"图片未选择"],在pictureBox1的Click事件中添加如下代码:
- private void pictureBox1_Click(object sender, EventArgs e)
- {
-
- OpenFileDialog op = new OpenFileDialog();
-
- op.Filter = "JPG图片|*.jpg|GIF图片|*.gif";
-
- if(op.ShowDialog()==DialogResult.OK)
- {
-
- this.label1.Text = "";
-
- FileStream fs = new FileStream(op.FileName, FileMode.Open);
-
- byte[] data = new byte[fs.Length];
- fs.Read(data, 0, data.Length);
- fs.Close();
-
- MemoryStream ms = new MemoryStream(data);
-
- this.pictureBox1.Image = Image.FromStream(ms);
- }
- }