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

时间:2013-07-22 18:19:31

标签: c# streamwriter

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

    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()”

的方法

我得到了第一个日期。

5 个答案:

答案 0 :(得分:2)

我可能会采用务实和简单的方式,但是跳过所有流内容并直接使用File类......

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

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

答案 1 :(得分:1)

这样做:

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

答案 2 :(得分:1)

您是否尝试过使用命令.Trimend('\ n')?

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

答案 3 :(得分:1)

您可以使用sw.Write和PRE-pend换行。不幸的是,这会在文件的开头给你一个空行。

答案 4 :(得分:1)

如另一个答案中所指出的,添加记录应该是调用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;