如何防止在文件中添加空行

本文关键字:添加 文件 何防止 | 更新日期: 2023-09-27 18:24:21

Im正在创建一个文本文件,最后一行是"

    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);
        }
    }

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

现在是一个DateTime对象

我用你的(Karl)代码创建了一个名为"readLastDate()"的方法

我得到了第一次约会。

如何防止在文件中添加空行

我可能已经习惯了实用和简单,但跳过所有流的内容,像这样直接使用File类。。。

string newLine = "";
if (!isFirstLine)
    newLine = Environment.NewLine;
File.AppendAllText(
    filePath, 
    string.Format("{0}{1}", newLine, DateTime.Now.ToString()));

您可以使用sw.Write并PRE挂起换行符。不幸的是,这将在文件开头给您一个空行。

您尝试过使用命令.Trimend('''n')吗?

http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx

这样做:

sw.Write(now.ToShortDateString());

这是StreamWriter.WriteLine.的MSDN文档

这是StreamWriter.Write.的MSDN文档

更新:

继续使用WriteLine,但更改从文件中读取值的方式:

using (StreamReader sr = new StreamReader(path))
{
    // 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;
        }
        // Is the line empty?
        if (line == String.Empty)
        {
            // Yes, so skip it
            continue;
        }
        // Here you process the non-empty line
    } while (true);
}

添加记录应该只需调用File.AppendAllText即可,正如另一个答案中所指出的那样。尽管我建议:

File.AppendAllText(filePath, DateTime.Now.ToString() + Environment.NewLine);

从文件中读取最后一个日期也很容易:

string lastGoodLine = "01/01/1900";
using (StringReader sr = new StringReader(filePath))
{
    while (!sr.EndOfStream)
    {
        string line = sr.ReadLine();
        if (!string.IsNullOrEmpty(line))
            lastGoodLine = line;
    }
}
return lastGoodLine;