EagL
EagL

Reputation: 77

Use current datetime as file path

I'm trying to make my program copy a file and rename it using it's current name and the current date. This is my current code, I know it's not working, but at least it shows what I want to do. I get an error at File.Copy... saying that An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll

var DAT = DateTime.Today;
string DATE = Convert.ToString(DAT);
File.Copy("D:/folder/file.json", "D:/folder/file" + DATE + ".json");

Upvotes: 0

Views: 1853

Answers (2)

Eugene Podskal
Eugene Podskal

Reputation: 10401

You can replace all invalid chars by getting them from Path.GetInvalidFileNameChars() and Path.GetInvalidPathChars()

public static class PathExt
{
    public static String ReplaceInvalidChars(String path, Char replacement = '_')
    {
        if (String.IsNullOrEmpty(path))
            throw new ArgumentException(paramName: nameof(path), message: "Empty or null path");

        var invalidChars = new HashSet<Char>(Path
            .GetInvalidFileNameChars()
            .Concat(Path.GetInvalidPathChars()));

        return new String(path
            .Select(ch =>
                invalidChars.Contains(ch) ?
                    replacement : ch)
            .ToArray());
    }
}

...

var dateTime = DateTime.Now.ToString();
var dateTimePath = PathExt.ReplaceInvalidChars(dateTime);
Console.WriteLine($"The time is {dateTime}");
Console.WriteLine($"The file is {dateTimePath}");
using (File.Create(dateTimePath))
{
    Console.WriteLine("File created");
}

Upvotes: 1

EagL
EagL

Reputation: 77

Maybe not the best solution, but it works.

string DAT = Convert.ToString(DateTime.Today);

        StringBuilder sb = new StringBuilder(DAT);

        sb.Replace(" ", "_");
        sb.Replace(":", "_");

        var DATE = sb.ToString();

File.Copy("D:/folder/file.json", "D:/folder/file" + DATE + ".json");

You can also replace the stringbuilder and String DAT... with just

string DATE = DateTime.Today.ToString("yyyy-MM-dd");.

Upvotes: 2

Related Questions