创建文件的文件路径,文件名每天更改
Creating a file path to a file, where the files name changes daily
我正在尝试获取文件名不断变化的文件的文件路径。到目前为止,我有一个名为 18052015.log 的特定日志文件的文件路径。我正在指定文件名和扩展名,18052015.log.
string strFilePath = @"\server-1\public\logs052015.log";
文件名与日期匹配。每天都会生成一个新文件。所以,明天会有一个名为 19052015.log
的文件
我唯一想检索的文件是名为 date.log 的文件,如 18052015.log 或 19052015.log。我不能使用该选项来检索任何扩展名为 .log 的日志,因为在同一个 logs 文件夹中还有许多其他文件,所有文件扩展名为 .log 例如 AFile.log、BFile.log、1File.log、2File.log。所以,下面的代码没有帮助。
string[] files = Directory.GetFiles(strFilePath, "*.log", SearchOption.AllDirectories);
我的问题是,如果文件名每天都在变化,我可以在不指定文件名的情况下检索该日志吗?
使用DateTime
这是一个小例子:
DateTime myTime = DateTime.Now;
string fileName = string.Format("{0}{1}{2}.log", myTime.Date, myTime.Month, myTime.Year);
DateTime.Now 为您提供计算机中的时间。然后你可以从结构中提取日期、月份和年份。
我认为您正在寻找指定格式的 DateTime.Now
:
string directoryPath = @"\server-1\public\logs;"
string fullLogPath = string.Format(@"{0}\{1:ddMMyyyy}.log", directoryPath, DateTime.Now);
合并所有解决方案:
string fullFilename = Path.Combine( @"\server-1\public\logs", string.Format("{0:ddMMyyyy}.log", myTime) );
并正确使用 Path.Combine 而不是 string'formatting around :-)
我正在尝试获取文件名不断变化的文件的文件路径。到目前为止,我有一个名为 18052015.log 的特定日志文件的文件路径。我正在指定文件名和扩展名,18052015.log.
string strFilePath = @"\server-1\public\logs052015.log";
文件名与日期匹配。每天都会生成一个新文件。所以,明天会有一个名为 19052015.log
的文件我唯一想检索的文件是名为 date.log 的文件,如 18052015.log 或 19052015.log。我不能使用该选项来检索任何扩展名为 .log 的日志,因为在同一个 logs 文件夹中还有许多其他文件,所有文件扩展名为 .log 例如 AFile.log、BFile.log、1File.log、2File.log。所以,下面的代码没有帮助。
string[] files = Directory.GetFiles(strFilePath, "*.log", SearchOption.AllDirectories);
我的问题是,如果文件名每天都在变化,我可以在不指定文件名的情况下检索该日志吗?
使用DateTime
这是一个小例子:
DateTime myTime = DateTime.Now;
string fileName = string.Format("{0}{1}{2}.log", myTime.Date, myTime.Month, myTime.Year);
DateTime.Now 为您提供计算机中的时间。然后你可以从结构中提取日期、月份和年份。
我认为您正在寻找指定格式的 DateTime.Now
:
string directoryPath = @"\server-1\public\logs;"
string fullLogPath = string.Format(@"{0}\{1:ddMMyyyy}.log", directoryPath, DateTime.Now);
合并所有解决方案:
string fullFilename = Path.Combine( @"\server-1\public\logs", string.Format("{0:ddMMyyyy}.log", myTime) );
并正确使用 Path.Combine 而不是 string'formatting around :-)