gpt4 book ai didi

c# - 如何防止在我的文件中添加空行?

转载 作者:太空宇宙 更新时间:2023-11-03 19:14:49 25 4
gpt4 key购买 nike

我正在创建一个文本文件,最后一行是“”

    private void lastRunDate()
{
String lastLine = readLastDate();
String[] date = lastLine.Split('/');
DateTime dt = new DateTime(Int32.Parse(date[2]), Int32.Parse(date[0]), Int32.Parse(date[1]));
DateTime currentDT = DateTime.Now;

argValue = 1;

if ((dt.Month == currentDT.Month) && (argValue == 0))
{
MessageBox.Show("This application has already been run this month");
this.Close();
}
}


private void AddRecordToFile()
{
DateTime now = DateTime.Now;
prepareToEmail();
string path = filepath;
bool dirtyData = true;
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.Write(now.ToShortDateString());
}
dirtyData = false;
}

if (dirtyData)
{
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(path))
{
sw.Write(now.ToShortDateString());
}
}
}

private String readLastDate()
{
using (StreamReader sr = new StreamReader(filepath))
{
// Initialize to null so we are not stuck in loop forever in case there is nothing in the file to read
String line = null;
do
{
line = sr.ReadLine();
// Is this the end of the file?
if (line == null)
{
// Yes, so bail out of loop
return "01/01/1900"; // I had to put something
}
// Is the line empty?
if (line == String.Empty)
{
// Yes, so skip it
continue;
}
// Here you process the non-empty line
return line;
} while (true);
}
}

是我用来创建文件(或附加文件)的内容

now 是一个 DateTime 对象

我使用您的 (Karl) 代码创建了一个名为“readLastDate()”的方法

我得到的是第一次约会。

最佳答案

我可能是务实和简单的方式,但是跳过所有流的东西并像这样直接使用 File 类......

string newLine = "";
if (!isFirstLine)
newLine = Environment.NewLine;

File.AppendAllText(
filePath,
string.Format("{0}{1}", newLine, DateTime.Now.ToString()));

关于c# - 如何防止在我的文件中添加空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17794594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com