+ -
当前位置:首页 → 问答吧 → C#

C#

时间:2011-12-15

来源:互联网

在C#中文件流这块,咋样在文件夹下面建文件?提供代码

作者: fxpbeyongman   发布时间: 2011-12-15

C# code


using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }
        }

        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}


msdn 例子

自己动手丰衣足食

file filestream 、、、


课本中的例子
C# code

        // <summary>
        // 在当前选择的目录中创建一个新的文本文件
        // </summary>
        private void NewFile()
        {
            InputFileName formFileName = new InputFileName();
            if (formFileName.ShowDialog(this) == DialogResult.OK)
            {
                string filename = tvDir.SelectedNode.FullPath +
                    "\\" + formFileName.txtFileName.Text + ".txt";
                StreamWriter sw = new StreamWriter(filename);
                if (sw != null)
                {
                    // 创建新文件后,向其中写入测试内容
                    sw.Write("新创建的文本文件\n演示基本的文件输入/输出操作");
                    sw.Close();
                    ListDirsAndFiles(tvDir.SelectedNode.FullPath);
                }
            }

        }

作者: MKing0412   发布时间: 2011-12-15

using (StreamWriter sw = new StreamWriter(filename))
  {
  sw.Write(filecontent);
  sw.Close();
  }

作者: caozhy   发布时间: 2011-12-15

要创建文本文件,可以这样
File.WriteAllText("文件名", "文件内容");  

假如要写入一个字节数组data(如果是个流,可以转换为字节数组)
FileStream fs = new FileStream("文件名", FileMode.Create);
fs.Write(data, 0, data.Length);
fs.Flush();
fs.Close();

作者: mayswind   发布时间: 2011-12-15