C# create file with text

时间:2018-01-23 19:15:28

标签: c# filestream streamwriter

I have problem with the FileStream. I want to create a file with my custom name, but it doesn't work. What I doing wrong ?

string nameoftest = Console.ReadLine()+".txt";
string path = "C:\C#test\" + nameoftest;
Console.WriteLine(path);
FileStream create = new FileStream(@"path", FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(create);

2 个答案:

答案 0 :(得分:3)

There are some mistakes in your code.

  • You should specify a valid path

  • You should pass path parameter for FileStream

  • You could use sw.WriteLine after declaring StreamWriter

  • It could be better to use using blocks to dispose streams when you finish your job

The code looks like

string nameoftest = Console.ReadLine() + ".txt";
string path = @"C:\" + nameoftest;
Console.WriteLine(path);
using (var fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
using (var sw = new StreamWriter(fileStream))
{
    sw.WriteLine("WriteSomething");
}

答案 1 :(得分:1)

基本上,@符号放错位置

错误分为两行:

  

string path =“C:\ C#test \”+ nameoftest;

应该是

  

string path = @“C:\ C#test \”+ nameoftest;

第二个错误是:

  

FileStream create = new FileStream(@“path”,FileMode.OpenOrCreate,   FileAccess.ReadWrite);

应该是

  

FileStream create = new FileStream(path,FileMode.OpenOrCreate,   FileAccess.ReadWrite);