【问题标题】:Write to text file, append text to the file, then load (read back)写入文本文件,将文本附加到文件中,然后加载(回读)
【发布时间】:2013-12-26 23:17:11
【问题描述】:

这是我在新课程中的代码:

public static void Save(List<Point> points, int imageWidth, int imageHeight, double originalFactor, double currentFactor)
{
   string appDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath);
   string textFile = "LightningsDistance.txt";
   string path = "LightningsDistance";
   string lightningsDistancePath = Path.Combine(appDirectory,path);
   string file = Path.Combine(lightningsDistancePath,textFile);
   if (!Directory.Exists(lightningsDistancePath))
   {
      Directory.CreateDirectory(lightningsDistancePath);
   }
   if (!File.Exists(file))
   {
      File.Create(file);
   }
}

文本文件的格式应该是这样的:

Image Width:             Image Height:        

Original Factor:         Current Factor:

Points Coordinates:

在点坐标中应该是这样的:

Coordinate 1: X = 21, Y = 25
Coordinate 2: X = 210, Y = 344

等等。列表点是这样的,例如在我看到的索引 0 中:X = 21 Y = 35

在 Form1 中,我有一个单击按钮,我称之为保存方法:

private void button2_Click(object sender, EventArgs e)
{
   CloudEnteringAlert.Save(picturebox1PointsCoordinates, img.Width, img.Height, factor, currentfactor);
}

我希望当我单击按钮时它会写入文本文件,如果我单击一次并绘制更多点并再次单击按钮,它会将新信息添加(附加)到相同的文本文件中格式如上,不要覆盖现有文件。

然后我有另一个调用 Load 方法的单击按钮。 Load 方法到目前为止还没有得到任何东西。刚上新课:

public static void Load()
{

}

我需要当我在任何时候单击加载时,它会从我保存的文本文件中读取信息,并且现在只会将点坐标分配回列表点。

【问题讨论】:

  • 你的问题是什么?
  • 检查流阅读器和流写入器,这就是你的答案。
  • 通常将数据而不是表单写入顺序文件。更常见的数据写为:100,200,50,40 等。写入结构化格式并跨多条记录读取将需要额外的代码。

标签: c# winforms


【解决方案1】:

File.AppendAllText(--) 就是你所需要的。它的语法类似于;

File.AppendAllText(string path,string contents,Encoding encoding);

所以你只需要使用适当的参数调用这个函数,就像这样;

File.AppendAllText(textFile,"Something to write...");

如果您使用正确的路径运行此语句 5 次,则生成的文件将包含五行文本,每行都有“Something to write...”

希望这是您的问题的解决方案。

【讨论】:

    猜你喜欢
    • 2014-08-07
    • 1970-01-01
    • 2022-01-21
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多