My app will upload pictures to the server, then display it back to the client, showing the pictures just uploaded. However, The function "Directory.CreateDirectory(virtualDirectory);" will not create a directory. Here is the sample code you can put a break point to reproduce and track the bug:
string absolutePath = Path.Combine(_environment.WebRootPath, "images\\Products"); string virtualPath = "\\images\\Products"; string absoluteDirectory = Path.Combine(absolutePath, ProductId.ToString()); string virtualDirectory = Path.Combine(virtualPath, ProductId.ToString()); bool tmpA = Directory.Exists(absoluteDirectory); bool tmpV = Directory.Exists(virtualDirectory); if (!Directory.Exists(virtualDirectory)) { Directory.CreateDirectory(virtualDirectory); }
If I replace the "Directory.CreateDirectory(virtualDirectory);" with the "Directory.CreateDirectory(absoluteDirectory);", a directory could be created. Then why bother using a Virtual Directory? Why not just using an absolute path? The reason is when I display the picture back, absolutePath will not work. The
<img src="@Url.Content(item.Path)" height="150" />
will only work on Virtual Path.
To summarize: when I upload a picture, I have to use Absolute Path in order to get the directory created; when I display this picture back, I have to use Virtual Path. My current work around is to keep both paths.