Fix WriteFile parameter order and create target directory if needed