将 .txt 配置文件读入字符串?

Read .txt configuration file into string?

我目前不得不尝试创建一种内务处理实用程序,我们可以将计划任务设置为 运行。

我已经将其硬编码为从特定文件夹中删除,它会删除超过 7 天的所有内容。

我想要一些灵活性,这样我就不必在每次找到需要管理的新目录时都创建一个新程序。

我想要一个包含两行的 configuration.txt 文件,一行是查找和删除文件的目录,另一行是早于 x 天的文件

我可以很好地阅读文件,只是不确定如何从文本文件创建字符串。

下面是我目前的工作程序,都是很基础的东西。

var files = new DirectoryInfo(@"c:\log").GetFiles("*.log")
foreach (var file in files)
{
    if (DateTime.UtcNow - file.CreationTimeUtc > TimeSpan.FromDays(7))
    {
        File.Delete(file.FullName);

如果有更多信息就好了,但是像这样的例子:

// Read file lines as strings
string[] lines = System.IO.File.ReadAllLines(@"C:\path\to\file.txt");
foreach (string line in lines) 
{
    string[] segs = s.Split('\t');
    string filename = segs[0];
    string age = segs[1];
    // call the relevant function for deleting files
    doDeletion(filename, age);
}

这是假设您的文件具有以下格式:

foldername1    7
foldername2    14

其中文件夹名称和年龄之间的间距是制表符

编辑: 现在注意到问题是针对一个文件,该文件包含一行文件夹名称,后跟一行年龄...在这种情况下,这可以解决问题:

string[] lines = System.IO.File.ReadAllLines(@"C:\path\to\file.txt");
if (lines.Length >= 2) 
{
    string filename = lines[0];
    string age = lines[1];
    doDeletion(filename, age);
}

如果您希望它尽可能简单:使用命令行参数。

class Program
{
    static void Main(string[] args)
    {
        string path;
        int days;

        if( args.Length < 2 ) return; 
        // ^^ You might want to throw some exception.
        // Or print a "Usage" string.

        path = args[0];
        // TODO: validate path, bail out if invalid

        if( !int.TryParse(args[1], out days) )
        {
             // handle parse error
        }
        // TODO: validate parsed value. I guess it shouldn't be negative or 0.

        DoYourThing( path, days );
    }
}

然后您可以从批处理文件中调用它。


如果你想在一次调用中处理多个目录并且想使用一个配置文件,你可以使用app.config 只是从 json 文件中读入并反序列化配置模型(还有更多选项)。

例子

config.json:

{
    items: [
       {
           path: "C:\test",
           days: 7
       },
       {
           path: "C:\test2",
           days: 5
       }
    ]
}

ConfigModel.cs

public class ConfigModel
{
    public Item[] Items {get; set;}
}

public class Item
{
    public string Path {get; set;}
    public int Days {get; set;}
}

读入:

var config = System.Text.Json.JsonSerializer.Deserialize<ConfigModel>(File.ReadAllText(@".\config.json"));

然后您可以简单地迭代您的配置:

foreach( var item in config.Items )
{
    DoYourThing(item.Path, item.Days);
}