Home > Enterprise >  System.IO Cannot create file with valid Paths?
System.IO Cannot create file with valid Paths?

Time:10-06

Lets get straight to it, Here's my code:

            DateTime today = DateTime.Today;
        if (!File.Exists(@"./Application/logs/"   today.ToString("d").Replace("/", ".")   ".txt"))
        {
            File.Create(@"./Application/logs/"   today.ToString("d").Replace("/", ".")   ".txt");
        }

For some reason its giving me this error.

Could not find a part of the path 'C:\Users\REDACTED\source\repos\Application\Application\bin\Debug\Application\logs\10.4.2021.txt'.'

I ran through some tests and went to its directory, The directory is there.

Thinking #1: I think its adding a dot at the end, if that's true can you find a way to prevent it? Thinking #2: It might be thinking this as a directory.

CodePudding user response:

One or more of the directories you've specified doesn't exist, that's why it's throwing a DirectoryNotFoundException.

Try creating the directories first, prior to creating the file.

var today = DateTime.Now;
var path = Path.Combine( @".\Application\logs", $"{today.ToString( "d" ).Replace( "/", "." )}.txt" );

var directory = Path.GetDirectoryName( path )!;

// You don't need to check if the directory exists first.
Directory.CreateDirectory( directory );

if ( !File.Exists( path ) )
{
    using var file = File.Create( path );    
    // Do some awesome stuff with your newly created file.             
}
  • Related