-1

I am going in circles with this. But all I am doing is, reading a simple text file into a byte array and reading a byte array into memory stream. Take a look at the code below.

var filePath = Directory.GetCurrentDirectory() + "\\TextFile1.txt";
var fileContent = System.IO.File.ReadAllBytes(filePath);

using (var ms = new System.IO.MemoryStream(fileContent)) {}

And I get an error "Illegal characters in path".

Here is my text file content:

ASJJDASDA

ASDJKAJSDJKASJDKLASJD

ASDASDASD++++++++++

++++++++

Any ideas?

Ashar Syed
  • 1,236
  • 6
  • 16
  • 28
  • 3
    _"Illegal characters in path"_ is usually an IO error. What's the value of `filePath` and what line do you get the error on? – stuartd Sep 20 '17 at 14:50
  • 1
    @MasterYoda what's the difference to the line OP already uses? – René Vogt Sep 20 '17 at 14:53
  • I dont see this being an issue with the memory stream, if he gets the current directory \\ will go down another directory whereas \ will stay within the current one. FYI i dont know where OP stores his textfile, its a suggestion not an answer... – Master Yoda Sep 20 '17 at 14:54
  • 2
    @MasterYoda now it won't compile because `\T` is not a valid escape character. If you mean `@"\TextFile1.txt"` we're at the starting point again, it's the same. But you're right, something must be wrong with the path. – René Vogt Sep 20 '17 at 14:57
  • 3
    You can use [Path.Combine()](https://msdn.microsoft.com/en-us/library/system.io.path.combine(v=vs.110).aspx) here to make your intentions clearer (and avoid the apparent confusion of how to use escape codes). – itsme86 Sep 20 '17 at 15:00
  • @RenéVogt It will compile just fine. It just won't work as expected. – itsme86 Sep 20 '17 at 15:00
  • 1
    Please verify the value of `filePath`. I somehow doubt that this is all the relevant code, because `Directory.GetCurrentDirectory()` must return a valid path with no trailing `\\` (and even that would not matter). So the code seems correct so far. – René Vogt Sep 20 '17 at 15:01
  • Print the value of filePath please and update your question. The problem has to have something to do with the filePath string and how its being escaped. – Master Yoda Sep 20 '17 at 15:02
  • @itsme86 don't know your compiler, but mine raises an error on "Unrecognized esacpe sequence"s. – René Vogt Sep 20 '17 at 15:02
  • 1
    OP's code works fine for me. As others have said, it would be handy to see what filePath contains. – spodger Sep 20 '17 at 15:05
  • I get a valid full path too. – PaulF Sep 20 '17 at 15:07
  • @RenéVogt You're correct. My bad. – itsme86 Sep 20 '17 at 15:17

1 Answers1

0

The above example should work.

Is it possible you have a weird instance where there is a backslash at the end of the Directory.GetCurrentDirectory()?

Try substituting

var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TextFile1.txt"); 

and see what happens then.

Phil Whittington
  • 2,144
  • 2
  • 16
  • 20