Search⌘ K
AI Features

Solution: Warehouse Stock Sync

Explore how to implement a warehouse stock synchronization solution by reading and writing JSON asynchronously in C#. Understand deserialization, safe file handling, and resource cleanup to update inventory data effectively using modern .NET techniques.

We'll cover the following...
C# 14.0
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
namespace CodingExercise;
public static class InventoryManager
{
public static async Task AddStockAsync(string filePath, int quantityToAdd)
{
string currentJson = await File.ReadAllTextAsync(filePath);
InventoryItem? item = JsonSerializer.Deserialize<InventoryItem>(currentJson);
if (item != null)
{
item.StockQuantity += quantityToAdd;
}
var options = new JsonSerializerOptions { WriteIndented = true };
string updatedJson = JsonSerializer.Serialize(item, options);
await File.WriteAllTextAsync(filePath, updatedJson);
Console.WriteLine("Inventory updated successfully.");
}
}
...