Надежное программирование


Исключение может возникнуть при следующих условиях.

· Файл существует и является файлом только для чтения.

· Имя пути имеет слишком большую длину.

· Диск может быть переполнен.

Безопасность

Если такого файла не существует, в примере создается новый файл. Если файл уже существует, приложение перезапишет его.


How to: Read XML from a File

This example uses the XmlTextReader class to extract the element names and text strings from a sample file and store the information in a string variable.

Example

System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("c:\\IntroToVCS.xml"); string contents = ""; while (reader.Read()) { reader.MoveToContent(); if (reader.NodeType == System.Xml.XmlNodeType.Element) contents += "<"+reader.Name + ">\n"; if (reader.NodeType == System.Xml.XmlNodeType.Text) contents += reader.Value + "\n"; } System.Console.Write(contents);

Compiling the Code

Copy the code and paste it into the Main method of a console application. Replace "c:\\IntroToVCS.xml" with the actual file name.

Note: The XML document must be well-formed.

Robust Programming

The following condition(s) may cause an exception:

· The path name may be too long.


Чтение XML из файла

Этот пример использует класс XmlTextReader для извлечения названий элементов и текстовых строк из файла образца и сохранения данных в строковой переменной.

Пример[18]

System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("c:\\IntroToVCS.xml"); string contents = ""; while (reader.Read()) { reader.MoveToContent(); if (reader.NodeType == System.Xml.XmlNodeType.Element) contents += "<"+reader.Name + ">\n"; if (reader.NodeType == System.Xml.XmlNodeType.Text) contents += reader.Value + "\n"; } System.Console.Write(contents);

Компиляция кода

Скопируйте код и вставьте его в метод Main консольного приложения.

Замените "c:\\IntroToVCS.xml" фактическим именем файла.

 

Примечание. Документ XML должен быть правильно сформированным.

Надежное программирование

Исключение может возникнуть при следующих условиях.

· Имя пути имеет слишком большую длину.


How to: Read Class Data from an XML File

This example uses the Deserialize method of the XmlSerializerclass to read data that is stored in an object in a sample file that is named IntroToVCS.xml.

Example

public class Book

{

public string title;

static void Main()

{

Book introToVCS = new Book();

System.Xml.Serialization.XmlSerializer reader = new

System.Xml.Serialization.XmlSerializer(introToVCS.GetType());

 

// Read the XML file.

System.IO.StreamReader file=

new System.IO.StreamReader("c:\\IntroToVCS.xml");

 

// Deserialize the content of the file into a Book object.

introToVCS = (Book) reader.Deserialize(file);

System.Windows.Forms.MessageBox.Show(introToVCS.title,

"Book Title");

}

}

Compiling the Code

You can compile the example directly at a command prompt, or paste the code into a console application by using the Visual Studio IDE. In the latter case, you must reference the System.Windows.Forms.dll file.

Robust Programming

The following condition(s) may cause an exception:

· The path name may be too long.




Дата добавления: 2022-05-27; просмотров: 122;


Поиск по сайту:

Воспользовавшись поиском можно найти нужную информацию на сайте.

Поделитесь с друзьями:

Считаете данную информацию полезной, тогда расскажите друзьям в соц. сетях.
Poznayka.org - Познайка.Орг - 2016-2024 год. Материал предоставляется для ознакомительных и учебных целей.
Генерация страницы за: 0.007 сек.