简体   繁体   中英

c# copying existing XML document with Linq to XML

I want to copy an existing .xml document inside of my bin/debug/ project Folder and create a new XML document being just a copy with an different name.

Here is what i have tried so far:

        XDocument ReleasesXML;

        if (XDocument.Load(id + ".xml") == null)
        {
            XDocument Version1 = XDocument.Load("SourcefileReleases.xml");
            ReleasesXML = new XDocument(Version1);

        }
        else
        {
            ReleasesXML = XDocument.Load(id + ".xml");
        }

If you only need to copy the file you could also write:

    string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
    string fileFrom = System.IO.Path.Combine(path, "from.xml");
    string fileTo = System.IO.Path.Combine(path, "to.xml");     
    Systen.IO.File.Copy(fileFrom, fileTo);

Reference

How about using just File functions?

if(File.Exists(id + ".xml"))
{
    File.Copy("SourcefileReleases.Xml", "newfile");  
}
else
{
    // logic
}

In my ASP.NET project this is the right code :

  // AppDomain.CurrentDomain.BaseDirectory = your project path

   XDocument Version1 = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "/Data/fileversion1.xml");
   XDocument  newFile = new XDocument(Version1); 
   //Save the file with a new name
   newFile.Save(AppDomain.CurrentDomain.BaseDirectory + "/Data/fileversion2.xml");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM