【问题标题】:How to write objects to a file如何将对象写入文件
【发布时间】:2016-06-24 13:03:14
【问题描述】:

可能是非常简单的事情,哈哈,但是我在试图找出我需要编写的代码以将 GetArea 计算写入文件时遇到了很多麻烦,这里是一些代码,所有帮助都表示赞赏:)

using System;
using System.IO;
namespace system
{
class Rectangle
{

    private double length;
    private double width;

    public void GetDetails()
    {
        Console.WriteLine("Enter Length: ");
        length = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("Enter Width: ");
        width = Convert.ToDouble(Console.ReadLine());
    }
    public double GetArea()
    {
        return length * width;
    }
    public void Display()
    {
        Console.WriteLine("Length: {0}", length);
        Console.WriteLine("Width: {0}", width);
        Console.WriteLine("Area: {0}", GetArea()); // this is what i need to be wrote to the file 
    }
    public void WriteToFile()
    {
        //this is the method where i need to find out the code to get the the getarea to write to the file

    }
}


class CalculateRectangle
{
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle();
        r.GetDetails();
        r.Display();
        r.WriteToFile(); //this is the main method in which i need the area of the rectangle to be wrote to the file
        Console.ReadLine();

    }
}

}

【问题讨论】:

  • 我看不到您将对象写入文件的代码。请发帖minimal reproducible example
  • 您是否研究过如何将文本写入文件?一个好的谷歌会抛出数千个关于如何做到这一点的结果......
  • System.IO.File.WriteAllText 怎么样?你试过了吗?

标签: c# visual-studio-2010 writetofile


【解决方案1】:

您可以使用File 类:

File.WriteAllText("filename.txt", GetArea().ToString());

这会将文件写入与exe 相同的文件夹中,否则使用@"C:\filename.txt" 之类的完整路径。如果遇到任何未经授权的异常,请以管理员身份运行 Visual Studio。

【讨论】:

    【解决方案2】:

    这会将其写入您选择的文件位置。

     public void writeToFile(){
    
     System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", getArea().toString());
    
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-20
      • 2011-09-25
      • 2011-12-11
      • 2021-05-20
      • 2020-06-28
      • 2015-05-15
      相关资源
      最近更新 更多