简体   繁体   English

StreamWriter无法在C#控制台中写入文件

[英]StreamWriter not writing to file in C# console

I'm new to programming and C# is the language I'm learning. 我是编程新手,而C#是我正在学习的语言。 My homework instructions are: 我的作业说明是:

Create a program named WritelnventoryRecords that allows you to enter data for items you sell at an online auction site and saves the data to a file. 创建一个名为WritelnventoryRecords的程序,该程序可让您输入在在线拍卖网站上出售的商品的数据,并将数据保存到文件中。 Create an Inventory class that contains fields for item number, description, and asking price. 创建一个库存类,其中包含项目编号,描述和要价字段。

The code I've written will not write to the text file, it's just blank. 我编写的代码不会写入文本文件,只是空白。 What am I missing? 我想念什么?

using System;
using System.IO;
class Inventory
{
    static void Main()
    {
        Console.Write("How many items would you like to enter? ");
        FileStream file = new FileStream("ItemsSold.txt", FileMode.Create, FileAccess.Write);
        StreamWriter writer = new StreamWriter(file);
        int num = Convert.ToInt32(Console.ReadLine());
        int itemNum = 0;
        string desc;
        double price;

        for (int count = 0; count < num; ++count)
        {
            Console.Write("Enter an item number: ");
            itemNum = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter the item description: ");
            desc = Console.ReadLine();
            Console.Write("Enter the item price (no dollar sign): ");
            price = Convert.ToDouble(Console.ReadLine());
            writer.WriteLine(itemNum + "," + desc + "," + price);
        }
        writer.Close();
        file.Close();
        Console.ReadLine();
    }
}

Thank you for your help. 谢谢您的帮助。

Your code works on my machine. 您的代码可以在我的机器上运行。 If it's still not works, you can try following steps: 如果仍然无法使用,请尝试以下步骤:

  1. When open the file stream, use "FileMode.OpenOrCreate" flag. 打开文件流时,使用“ FileMode.OpenOrCreate”标志。
  2. Reset the file using "file.SetLength(0);" 使用“ file.SetLength(0);”重置文件 just after create the file steam. 在创建文件流之后。
  3. Flush the buffer before close the file stream: "writer.Flush();" 在关闭文件流之前刷新缓冲区:“ writer.Flush();”

    === EDIT === ===编辑===

And yes, like @Preston Guillot posted, check if you are opening the right file. 是的,就像@Preston Guillot发布的一样,检查是否打开了正确的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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