简体   繁体   中英

I'm trying to create a file using FileStream but getting an exception why?

This is the code :

public OptionsFile(string settings)
    {
        
        if (File.Exists(settings))
        {
            
        }
        else
        {
        FileStream fs=File.Create(settings);

        fs.Close();
        }
        
        path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
        Options_File = settings;
        
    }

On the line : FileStream fs=File.Create(settings);

For some reason it's unable to create the file . In Form1 i did in the constructor :

Options_DB.Get_Video_File();

Now in Options_DB class using a breakpoint it's doing :

namespace test
{
    
    static class Options_DB
    {
        static string settings_dir;
        static string settings_file;
        static OptionsFile setting_file;
        static string path_settings;
        static string path_exe;
        static string outPutVideoFileDirectory;

        static Options_DB()
        {
            // ---  O P E N N I N G   S E T T I N G   F I L E   ;
            path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
            path_settings = Path.GetDirectoryName(Application.LocalUserAppDataPath);
            settings_file = "\\settings.txt";
            settings_dir = path_settings + @"\settings";
            setting_file = new OptionsFile(settings_dir + settings_file);

Then in the OptionsFile it's doing :

public OptionsFile(string settings)
    {
        
        if (File.Exists(settings))
        {
            
        }
        else
        {
        FileStream fs=File.Create(settings);

        fs.Close();
        }
        
        path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
        Options_File = settings;
        
    }

I used a breakpoint in the OptionsFile and see that settings contain the user directory with the settings.txt file but for some reason it's unable to make the line:

FileStream fs=File.Create(settings);

It stop on Form1 on the line : Options_DB.Get_Video_File();

The type initializer for 'ScreenVideoRecorder.Options_DB' threw an exception

System.TypeInitializationException was unhandled
  HResult=-2146233036
  Message=The type initializer for 'ScreenVideoRecorder.Options_DB' threw an exception.
  Source=ScreenVideoRecorder
  TypeName=ScreenVideoRecorder.Options_DB
  StackTrace:
       at ScreenVideoRecorder.Options_DB.Get_Video_File()
       at ScreenVideoRecorder.Form1..ctor() in d:\C-Sharp\ScreenVideoRecorder\ScreenVideoRecorderWorkingVersion\Form1.cs:line 54
       at ScreenVideoRecorder.Program.Main() in d:\C-Sharp\ScreenVideoRecorder\ScreenVideoRecorderWorkingVersion\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.IO.DirectoryNotFoundException
       HResult=-2147024893
       Message=Could not find a part of the path 'C:\Users\bout0_000\AppData\Local\ScreenVideoRecorder\ScreenVideoRecorder\settings\settings.txt'.
       Source=mscorlib
       StackTrace:
            at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
            at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
            at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
            at System.IO.File.Create(String path)
            at DannyGeneral.OptionsFile..ctor(String settings) in d:\C-Sharp\ScreenVideoRecorder\ScreenVideoRecorderWorkingVersion\OptionsFile.cs:line 73
            at ScreenVideoRecorder.Options_DB..cctor() in d:\C-Sharp\ScreenVideoRecorder\ScreenVideoRecorderWorkingVersion\Options_DB.cs:line 29
       InnerException: 

For some reason after following the breakpoint steps it's unable to create the FileStream . I guess something is wrong with the line : FileStream fs=File.Create(settings);

settings contins when trying to create it :

"C:\\Users\\user name\\AppData\\Local\\project dir\\project dir\\settings\\settings.txt"

But it never create it .

If you read the inner exception, you can see that the issue is that the settings directory does not exist. You can remedy this by calling Directory.CreateDirectory , which creates all directories and subdirectories in the specified path that do not already exist. (It does nothing if the directory does already exist.)

I would also recommend replacing your manual path concatenation with Path.Combine calls.

settings_dir = Path.Combine(path_settings, "settings");
Directory.CreateDirectory(settings_dir);  // create directory

settings_file = "settings.txt";
setting_file = new OptionsFile(Path.Combine(settings_dir, settings_file));

The exception is clear: The path "C:\\Users\\bout0_000\\AppData\\Local\\ScreenVideoRecorder\\ScreenVideoRecorder\\settings\\"

doesn't exists.

Notice that this path is different from:

"C:\\Users\\user name\\AppData\\Local\\project dir\\project dir\\settings\\"

The exception states:

Could not find a part of the path 'C:\\Users\\bout0_000\\AppData\\Local\\ScreenVideoRecorder\\ScreenVideoRecorder\\settings\\settings.txt'

So you need to check that the file or folder exists or that you have permissions to write to that particular folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM