我无法使用StreamWriter类创建新的.txt文件

时间:2018-06-29 11:52:32

标签: c# streamwriter

这是我的代码...

string path = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Music", "stream.txt");

StreamWriter sw = new StreamWriter("stream.txt");
sw.WriteLine("i am stream");
sw.Close();

2 个答案:

答案 0 :(得分:0)

选中此一项:-

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);
            }
        }
    }
}

Reference

答案 1 :(得分:0)

您几乎在那里有了解决方案:

string path = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"),"Music", "stream.txt");

            StreamWriter sw = new StreamWriter(path);
            sw.WriteLine("i am stream");
            sw.Close();

您只需要使用创建的路径变量:)

执行后,请记住在“音乐”文件夹中查找stream.txt文件