创建在前面加上日期一个新的.txt文件,C# [英] Creating a new .txt file with date in front, C#

查看:176
本文介绍了创建在前面加上日期一个新的.txt文件,C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得以下内容:[今天的日期] ___ [textfilename] .TXT从下面的代码:

 使用系统; 
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
:使用System.IO;

命名空间ConsoleApplication29
{
类节目
{
静态无效的主要(字串[] args)
{
将writeToFile( );

}

静态无效将writeToFile()
{

StreamWriter的SW;
SW = File.CreateText(C:\\testtext.txt);
sw.WriteLine(这只是一个测试);
sw.Close();
Console.WriteLine(文件创建成功);



}
}
}

我试图把在 DateTime.Now.ToString(),但我不能结合字符串。



有人能帮助我吗?我想在我创建新的文本文件的标题前面的日期。


解决方案

 静态无效将writeToFile(字符串目录,字符串名称)
{
字符串文件名=的String.Format({0:YYYY-MM-DD} __ {1},DateTime.Now,名) ;
路径字符串= Path.Combine(目录下,文件名);使用
(StreamWriter的SW = File.CreateText(路径))
{
sw.WriteLine(这只是一个测试);
}
}

要拨打:

 将writeToFile(@C:\mydirectory,mYfILEname的); 

请注意以下几点:




  • 指定一个自定义格式字符串的日期,并避免使用非法字符在NTFS。

  • 包含与'@'字符串文字标记路径前缀字符串,所以你不''T必须逃离路径中的反斜杠。

  • 联合路部分与Path.Combine(),并避免与路径分隔符碴左右。

  • 创建的StreamWriter时使用using块;退出块将处置
    的StreamWriter,并自动关闭你的文件。


I am trying to get the following: [today's date]___[textfilename].txt from the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication29
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteToFile();

        }

        static void WriteToFile()
        {

            StreamWriter sw;
            sw = File.CreateText("c:\\testtext.txt");
            sw.WriteLine("this is just a test");
            sw.Close();
            Console.WriteLine("File created successfully");



        }
    }
}

I tried putting in DateTime.Now.ToString() but i cannot combine the strings.

Can anybody help me? I want the date in FRONT of the title of the new text file I am creating.

解决方案

static void WriteToFile(string directory, string name)
{
    string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now, name);
    string path = Path.Combine(directory, filename);
    using (StreamWriter sw = File.CreateText(path))
    {
    	sw.WriteLine("This is just a test");
    }
}

To call:

WriteToFile(@"C:\mydirectory", "myfilename");

Note a few things:

  • Specify the date with a custom format string, and avoid using characters illegal in NTFS.
  • Prefix strings containing paths with the '@' string literal marker, so you don''t have to escape the backslashes in the path.
  • Combine path parts with Path.Combine(), and avoid mucking around with path separators.
  • Use a using block when creating the StreamWriter; exiting the block will dispose the StreamWriter, and close the file for you automatically.

这篇关于创建在前面加上日期一个新的.txt文件,C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆