可能是一件令人难以置信的事情哈哈但是我在试图找出我需要编写的代码以便将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();
}
}
}
答案 0 :(得分:1)
您可以使用File
类:
File.WriteAllText("filename.txt", GetArea().ToString());
这会将文件写入与exe
相同的文件夹中,否则请使用@"C:\filename.txt"
之类的完整路径。如果您遇到任何未经授权的异常,请以管理员身份运行Visual Studio。
答案 1 :(得分:0)
这会将其写入您选择的文件位置。
public void writeToFile(){
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", getArea().toString());
}