简体   繁体   中英

I am unable to create new .txt file using StreamWriter Class

Here is my code...

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

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

Check This one:-

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

You almost had the solution there:

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

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

You just had to use the path variable you created :)

After execution remember to look in the Music folder for the stream.txt file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM