Search code examples
asp.netblazorblazor-webassemblywebassembly

I cant read an xml file on blazor


As i said i cant read a local XML file.

Im using this path that is on my pc: "C:\Users\Autoescuela\Desktop\Models\models.xml"

        public Models SerializeModels(string path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Models));
            Models? models;
            using (Stream reader = new FileStream(path, FileMode.Open))
            {
                models = serializer.Deserialize(reader) as Models;
            }

            return models;

        }

and this is the error :

Unhandled exception rendering component: Could not find file '/C:\Users\Autoescuela\Desktop\Models\models.xml'.

I tryed to put my folder Models on wwwroot folder, but i still having the same problem.

Unhandled exception rendering component: Could not find file '/~\Models\models.xml'

Unhandled exception rendering component: Could not find file '/Models\models.xml'.

I also need use this XML in other application that uses the same xml and update on both at the same time, but i if its needed to use on wwwroot isnt a problem.


Solution

  • I found a solution. I take the data from the xml like this

    protected override async void OnInitialized()
    {
    
        models = XqueryFunctions.GetModels(await http.GetStringAsync("Models/models.xml"));
    }
    

    and then I load with .loadXml()

        public static XmlNodeList Xquery(string xpath, string document)
        {
    
            XmlDocument xml = new();
            xml.LoadXml(document);
            return xml.SelectNodes(xpath);
    
    
        }
    

    I know isnt a good aswer but it works, if some one can take the file instead of the file string I would really appreciate it.