.NET (PowerShell) Concurrent file usage (locking, while still allowing read access)

前端 未结 3 2191
面向向阳花
面向向阳花 2021-01-15 22:27

I have an XML file that I need to have concurrent access to. I do not need concurrent write, but I do need concurrent read. The perscribe

3条回答
  •  一向
    一向 (楼主)
    2021-01-15 22:40

    May I suggest a slightly different approach to it all. You can do the following with PowerShell which allows you to avoid the issue on the reads. My XML navigation may be a little off, but it will work as described here.

    function Read-Only()
    {
        $database = [xml](Get-Content $filename)
        foreach($item in $database.Items)
        {
            Write-Host "Item name $item.Name"
        }
     }
    

    Now you can keep your same write function or you can do it all with PowerShell. If you wanted to do it with PowerShell you can do something like this.

    function Read-Write()
    {
        $database = [xml](Get-Content $filename)
    
        $itemname = Read-Host "Enter an item name ('quit' to quit)"
        while($itemname -ne 'quit')
        {
            $newItem = $database.CreateElement("item")
            $newItem.SetAttribute("Name", $itemname)
            $database.Items.AppendChild($newItem)
            # You can also save all the changes up and write once.
            $database.Save($filename)
            $itemname = Read-Host "Enter an item name ('quit' to quit)"
        }
    }
    

提交回复
热议问题