Save Data with StreamWriter - false directory name?

Jim Jupiter 66 Reputation points
2021-09-12T19:55:42.377+00:00

Hi

I try to save some Data with streamwriter - but it didn't work

my code is

string fileName = "hsl.dat";
string aktVerz = Directory.GetCurrentDirectory();
string pathString = aktVerz + @"\Misc";
string currentFile = pathString + @"\" + fileName;
StreamWriter Swriter = new StreamWriter(currentFile);

Error appears "Could not find a part of the path" but path exists ???

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,470 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Viorel 113.7K Reputation points
    2021-09-12T20:19:12.383+00:00

    Try another variable:

    string aktVerz = Path.GetDirectoryName( Assembly.GetEntryAssembly( ).Location );


  2. WayneAKing 4,921 Reputation points
    2021-09-12T20:30:45.457+00:00

    my code is

    string fileName = "hsl.dat";
    string aktVerz = Directory.GetCurrentDirectory();
    string pathString = aktVerz + @"\Misc";
    string currentFile = pathString + @"\" + fileName;
    StreamWriter Swriter = new StreamWriter(currentFile);

    Are you sure that a subdirectory/folder named Misc already
    exists on that path? If it doesn't then you will get that
    error. If it does already exist your code should not error.

    StreamWriter will create a new file, but it will NOT create
    a new folder/directory from the path supplied.

    • Wayne

  3. WayneAKing 4,921 Reputation points
    2021-09-12T22:03:58.613+00:00

    yeah I'm sure :)

    I doubt it. While there may be a subdir named Misc on
    some path, the OS is saying one does NOT exist on the
    path that IT sees as the current directory.

    You may be making an incorrect assumption about what
    IS the current directory when you run the program.
    It often will be different when the program is run
    in the IDE than when it is run from a command prompt
    or from File Explorer. It will be different when you
    run in the IDE from a Debug build than when you run
    from a Release build.

    You should be stepping through the program in the
    debugger and examining each string to confirm that
    they contain what you expect. Or display each string
    on the console or in a MessageBox so you can confirm
    the contents.

    • Wayne