C# 如何将对象写入文件
可能是非常简单的事情哈哈,但是我在试图找出需要编写的代码以将GetArea计算写入文件时遇到了很多麻烦。下面是一些代码,非常感谢:C# 如何将对象写入文件,c#,visual-studio-2010,writetofile,C#,Visual Studio 2010,Writetofile,可能是非常简单的事情哈哈,但是我在试图找出需要编写的代码以将GetArea计算写入文件时遇到了很多麻烦。下面是一些代码,非常感谢: using System; using System.IO; namespace system { class Rectangle { private double length; private double width; public void GetDetails() { Console.WriteLine(
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();
}
}
}您可以使用文件类:
File.WriteAllText("filename.txt", GetArea().ToString());
这将把文件写入exe所在的文件夹,否则使用完整路径,如@C:\filename.txt。如果遇到任何未经授权的异常,请以管理员身份运行Visual studio。这会将其写入您选择的文件位置
public void writeToFile(){
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", getArea().toString());
}
我看不到将对象写入文件的代码。请发帖,你有没有研究过如何将文本写入文件?一个好的谷歌会在如何做到这一点上给出成千上万的结果……那么仅仅是System.IO.File.writealText呢?你试过了吗?