Saving XML file to disk

Refresh

March 2019

Views

1.6k time

1

I'm trying to save an XDocument object to disk, as an .xml file. The object seems well formed in the debugger, I'm only having an issue saving the actual file. Here is what I'm doing :

       //ofx is an `XElement` containing many sub-elements of `XElement` type
        XDocument document = new XDocument(ofx);

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        settings.Indent = true;

        //destinationPath is a string containing a path, like this
        // e.g : "C:\\Users\\Myself\\Desktop"  
        using (var stream = File.Create(destionationPath + @"export.xml"))
        {
            List<byte[]> header = new List<byte[]>();

            byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);

            List<string> headers = new List<string>();
            headers.Add("foo"); 

            // Just adding some headers here on the top of the file. 
            // I'm pretty sure this is irrelevant for my problem

            foreach (string item in headers)
            {
                header.Add(Encoding.ASCII.GetBytes(item));
                header.Add(newline);
            }

            header.Add(newline);

            byte[] bytes = header.SelectMany(a => a).ToArray();

            stream.Write(bytes, 0, bytes.Length);
            using (var writer = XmlWriter.Create(stream, settings))
            {
                document.Save(writer);
            }

        }

Whenever I call this, I have no file in the target directory.

Notes : The directory is well-formed too, as well as the file name. This is verified in the code.

1 answers

2

Возможно, вы создаете путь плохо. После прокомментируете у вас есть

string destionationPath = "C:\\Users\\Myself\\Desktop";
destionationPath + @"export.xml" // evaluates to: "C:\\Users\\Myself\\Desktopexport.xml"

У вас не хватает "\\"между каталогом и именем файла.

Следующий код работает для меня.

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Tmp();
        }

        public static void Tmp()
        {

            //ofx is an `XElement` containing many sub-elements of `XElement` type
            XDocument document = new XDocument(new XElement("myName", "myContent"));

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            settings.Indent = true;

            //destinationPath is a string containing a path, like this
            // e.g : "C:\\Users\\Myself\\Desktop"  
            string destionationPath = "D:\\Temp\\xml_test\\";
            using (var stream = File.Create(destionationPath + @"export.xml"))
            {
                List<byte[]> header = new List<byte[]>();

                byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);

                List<string> headers = new List<string>();
                headers.Add("foo");

                // Just adding some headers here on the top of the file. 
                // I'm pretty sure this is irrelevant for my problem

                foreach (string item in headers)
                {
                    header.Add(Encoding.ASCII.GetBytes(item));
                    header.Add(newline);
                }

                header.Add(newline);

                byte[] bytes = header.SelectMany(a => a).ToArray();

                stream.Write(bytes, 0, bytes.Length);
                using (var writer = XmlWriter.Create(stream, settings))
                {
                    document.Save(writer);
                }
            }
        }
    }
}

Чтобы избежать подобных ситуаций , никогда не создать создать путь по yoursef. Используйте Pathкласс вместо этого:

Path.Combine(destionationPath, @"export.xml")