2013-07-26 2 views
1

C#에서는 XML 파일이 만들어 졌는지 확인하고 파일을 만들지 않은 경우 XML 선언, 메모 및 부모 노드를 만들려고합니다.폼로드시 XML 파일을로드 할 때 오류 발생

:

내가 그것을로드하려고, 그것은 나에게이 오류 준다 "프로세스가 파일에 액세스 할 수 없습니다. 'C를 : \ FileMoveResults \ Applications.xml'다른 프로세스에서 사용하고 있기 때문에"

작업 관리자가 열려 있지 않은지 확인하고 열려있는 응용 프로그램이 없는지 확인했습니다. 무슨 일이 벌어지고 있는지에 대한 아이디어가 있습니까? 여기

//check for the xml file 
if (!File.Exists(GlobalVars.strXMLPath)) 
{ 
//create the xml file 
File.Create(GlobalVars.strXMLPath); 

//create the structure 
XmlDocument doc = new XmlDocument(); 
doc.Load(GlobalVars.strXMLPath); 

//create the xml declaration 
XmlDeclaration xdec = doc.CreateXmlDeclaration("1.0", null, null); 

//create the comment 
XmlComment xcom = doc.CreateComment("This file contains all the apps, versions, source and destination paths."); 

//create the application parent node 
XmlNode newApp = doc.CreateElement("applications"); 

//save 
doc.Save(GlobalVars.strXMLPath); 

내가이 문제를 해결하려면 사용하여 종료 코드입니다 : 여기

내가 사용하고있는 코드입니다 XML 파일 경우 (File.Exists (GlobalVars 확인 //!. strXMLPath)) {

사용 (XmlWriter를 xWriter = XmlWriter.Create (GlobalVars.strXMLPath)) { xWriter.WriteStartDocument(); xWriter.WriteComment ("이 파일에는 모든 응용 프로그램, 버전, 소스 및 대상 경로가 포함되어 있습니다."); xWriter.WriteStartElement ("application"); xWriter.WriteFullEndElement(); xWriter.WriteEndDocument(); }

+0

빈 파일의'doc.Load()'는 예외를 throw합니다. – SLaks

답변

2

I는 다음과 같이 제안 :

string filePath = "C:/myFilePath"; 
XmlDocument doc = new XmlDocument(); 
if (System.IO.File.Exists(filePath)) 
{ 
    doc.Load(filePath); 
} 
else 
{ 
    using (XmlWriter xWriter = XmlWriter.Create(filePath)) 
    { 
     xWriter.WriteStartDocument(); 
     xWriter.WriteStartElement("Element Name"); 
     xWriter.WriteEndElement(); 
     xWriter.WriteEndDocument(); 
    } 

    //OR 

    XmlDeclaration xdec = doc.CreateXmlDeclaration("1.0", null, null); 
    XmlComment xcom = doc.CreateComment("This file contains all the apps, versions, source and destination paths."); 
    XmlNode newApp = doc.CreateElement("applications"); 
    XmlNode newApp = doc.CreateElement("applications1"); 
    XmlNode newApp = doc.CreateElement("applications2"); 
    doc.Save(filePath); //save a copy 
} 

코드가 현재 문제가되는 이유는이다 : File.Create 파일을 생성하고 파일 스트림을 열고, 다음 당신이 그것의 사용을 결코 이 라인에 (닫 결코) :

//create the xml file 
File.Create(GlobalVars.strXMLPath); 

당신이

//create the xml file 
using(Stream fStream = File.Create(GlobalVars.strXMLPath)) { } 
,536처럼 뭔가를 한 경우

그렇다면 사용 중 예외가 발생하지 않을 것입니다. 지정된 경로에 XML을 저장하기 위해 스트림을 사용하는 FileMode 다음 FileMode.Create 및 설정 XmlDocument.Load 만 당신은 스트림을 만들 수 이미

+0

감사합니다. 첫 번째 옵션은 XmlWriter를 사용하여 작업했습니다! – user2619395

2

File.Create()은 닫힐 때까지 파일을 잠그는 FileStream을 반환합니다.

File.Create()으로 전화 할 필요가 없습니다. doc.Save()이 파일을 만들거나 덮어 씁니다.

0

을하여 만드는 작업, 파일을 생성하지 않습니다 측면 참고로

, .

using (System.IO.Stream stream = new System.IO.FileStream(GlobalVars.strXMLPath, FileMode.Create)) 
{ 
    XmlDocument doc = new XmlDocument(); 
    ... 
    doc.Save(stream); 
} 
관련 문제