为什么我的StreamWriter没有保存到文本文件?

问题描述:

我没有问题,阅读fruits.txt文件与streamreader但写入newFruits.txt似乎无法正常工作。为什么我的StreamWriter没有保存到文本文件?

我运行的代码,没有任何错误,然后检查newFruits.txt文件,看它仍是空白。如果有帮助,我有以下newFruits.txt屏幕截图的属性窗口。我检查了其他问题,他们似乎并不相似或可以理解。有什么建议么?

using System; 
using System.IO; 
using System.Globalization; 
using System.Threading; 

class FruityLoops 
{ 
    static void Main() 
    { 
     Console.WriteLine("Loading and sorting fruits..."); 
     CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; 
     TextInfo textInfo = cultureInfo.TextInfo; 


     StreamReader fruitreader = new StreamReader("fruits.txt"); 
     string fruitList = fruitreader.ReadLine(); 
     char x = ','; 
     string[] fruitArray1 = fruitList.Split(x); 
     Array.Sort(fruitArray1); 
     fruitreader.Close(); 

     StreamWriter fruitwriter = new StreamWriter("newFruits.txt"); 
     fruitwriter.WriteLine(fruitArray1); 
     fruitwriter.Close(); 

    } 
} 

这是我的属性菜单的picture我正在尝试写的文本文件。看到任何问题?不知道这是一个设置问题还是代码问题。

这里是我的fruits.txt文件的picture了。

你应该同时传递一个串线使用“的WriteLine”方法时:

 for (int i = 0; i < fruitArray1.Length -1 ; i++) 
     { 
      fruitwriter.WriteLine(fruitArray1[i]) 
     } 
+0

这工作。谢谢! –

代码工作,但它节省了newFruits.txt文件到BIN \ Debug或Bin \ Release目录的程序运行在那里,不是转换为newFruits.txt文件,它是您项目的一部分。

主要意见:

  1. 该代码会写System.String[]到输出文件
  2. StreamWriter S的关系被包裹在using语句。

您正在将Array传递给WriteLine方法,实际上您应该将字符串传递给它。

StreamWriter.WriteLine

要写入文件异步。你应该使用下面的asyncawait

static async void WriteTextAsync(string text) 
{ 
    // Set a variable to the My Documents path. 
    string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 

    // Write the text asynchronously to a new file named "WriteTextAsync.txt". 
    using (StreamWriter outputFile = new StreamWriter(mydocpath + @"\WriteTextAsync.txt")) { 
     await outputFile.WriteAsync(text); 
    } 
} 

使用下面的代码,通过直接传递string[],而不是通过使用StreamWriter写。

string[] lines = { "line 1", "line 2" }; 
File.WriteAllText("newFruits.txt", ""); 
File.AppendAllLines("newFruits.txt", lines); 

你也可以这样做。

string path = @"c:\temp\MyTest.txt"; 

    // This text is added only once to the file. 
    if (!File.Exists(path)) 
    { 
     // Create a file to write to. 
     string[] createText = { "Hello", "And", "Welcome" }; 
     File.WriteAllLines(path, createText, Encoding.UTF8); 
    } 

Reference

+0

有什么*“要异步写入文件*以解决此问题? – Jim

  1. 你没有提到数组的元素。

你应该给你想要检索的元素的索引。

fruitwriter.WriteLine(fruitArray1[0]); 

代替

fruitwriter.WriteLine(fruitArray1); 
  1. 即使它写入时,程序将只读取和写入一行。

    使用循环读取和写入行,并在读取所有行后关闭StreamReader和StreamWriter。

开始=>