Blazor

Let's Fix Blog Code to be cross platform compatible.

In using the Blazing Blog V2 template for our blog, I found that it was written to work on Windows. It is not difficult to make your code cross-platform compatible. Check out the following examples.

Hugh Flanagan

Changes Made:

  • Forward slashes (/) have replaced backslashes (\) in all file paths. This ensures compatibility across Linux, macOS, and Windows environments.

Why Use Forward Slashes?

  • Linux and macOS: These platforms require paths to be defined with forward slashes.
  • Windows: Windows can handle both forward and backward slashes, making forward slashes the cross-platform compatible choice.

Best Practice:

Always use forward slashes (/) in paths in your .csproj file and other configuration files to ensure that your project works seamlessly on both Linux and Windows.


This code is meant to be run on Windows host.


Needs Update to be cross platform. 

private void DeleteExistingImage(string imageUrl) 

var imagePath = imageUrl.Replace("/", "\\"); 

var fullPath = Path.Combine(WebHostEnvironment.WebRootPath, imagePath); 

try { 

File.Delete(fullPath); 

catch{} }


Update to be cross-platform to look something like this:

private void DeleteExistingImage(string imageUrl)

{

  // Replace the forward slashes with the platform-specific directory separator character

  var imagePath = imageUrl.Replace('/', Path.DirectorySeparatorChar);

  // Combine the WebRoot path with the image path to form the full file system path

 var fullPath = Path.Combine(WebHostEnvironment.WebRootPath, imagePath);

 try

 {

  // Delete the file if it exists

   if (File.Exists(fullPath))

   {

    File.Delete(fullPath);

   }

 }

  catch (Exception ex)

  {

   // Optionally log the exception

   Console.WriteLine($"Error deleting file: {ex.Message}");

  }

}

Become a member
Get the latest news right in your inbox. It's free and you can unsubscribe at any time. We hate spam as much as we do, so we never spam!
Read next

Let's Build a Blog Site with Blazor.

Building a personal blog is a great way to document projects, share insights, and showcase technical skills. Using Blazor Server offers a seamless development experience, allowing you to use C# for both front-end and back-end, while benefiting from server-side rendering and integrated security. In this post, we'll explore why Blazor Server is an ideal choice for building a blog site and how it can help you grow as a developer.

Hugh Flanagan Oct 11
An unhandled error has occurred. Reload 🗙