2

I need to write an image (e.g. .iso, .img) to an SD card. The use shouldn't matter, but it happens to be writing a bootable image to an sdcard for a rasperry pi.

On Linux/Mono, I would do something along the following:

using (var stream = File.OpenWrite("H:\\"))
{
    //Copy the .img file to stream
}

However, I'm doing this on a Windows machine. This throws:

UnauthorizedAccessException: "Access to the path 'H:\' is denied."

Igor
  • 60,821
  • 10
  • 100
  • 175
RQDQ
  • 15,461
  • 2
  • 32
  • 59
  • 1
    Not to insult your intelligence, but is the SD card mounted under H:\ on your Windows host too? – ajeh Sep 20 '16 at 19:07
  • 1
    I am very surprised that it works like that on Linux/Mono. I did not think it worked like that. – Scott Chamberlain Sep 20 '16 at 19:10
  • 2
    Then you simply cannot use a file stream to write to a device like you are trying. In Windows you are trying to open a non-exising file and getting a correct error. – ajeh Sep 20 '16 at 19:11
  • @Igor - I don't think it's a permissions issue. The process is running under administrator credentials. ajeh - I know the above approach doesn't work - that's why I'm asking the question. – RQDQ Sep 20 '16 at 19:12
  • 1
    I think the problem here is that you are trying to open a file `OpenWrite()`, but supplying only a drive ID. There is no file to open at that location. You should probably instead, create a new stream with the image data, and write it to the path rather than trying to open the path to allow for writing. – Evan L Sep 20 '16 at 19:14
  • 3
    You may want to look at [this SO question](http://stackoverflow.com/q/38190/80274), it is about doing a raw read to the filesystem instead of a raw write like you are, so you will need to update it with the methods to write out. – Scott Chamberlain Sep 20 '16 at 19:15
  • @EvanL hit the nail on the head. You are using the `File.OpenWrite`, key word here is `File`. You need to supply a file on disk like `@"H:\someFile.img"`; Its not what you want to do but that is all you can do with that type (System.IO.File). – Igor Sep 20 '16 at 19:15
  • I should add that my explanation does not take into account writing bootable media. For that you will likely have to hit P/Invoke or some Win32 API's to do the direct disk access. I could be wrong, but I doubt simply writing an image to a disk would make the device a bootable device. – Evan L Sep 20 '16 at 19:16
  • @ScottChamberlain Need to get reading glasses, I suppose :) Deleting my comment. – Jesse C. Slicer Sep 20 '16 at 19:22
  • I found this open source project that does exactly what I need (albeit in c): https://github.com/pbatard/rufus I'll use it as a starting point. – RQDQ Sep 21 '16 at 12:15

1 Answers1

0

In the end, I chose to just execute RuFus:

https://rufus.akeo.ie/

A fully integrated solution would be nicer, but this was an easy way to just 'maie it go'.

RQDQ
  • 15,461
  • 2
  • 32
  • 59