Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

di.CreateSubdirectory("Subdir1"); //---c:\My Folder\Subdir1---

di.CreateSubdirectory("Subdir2"); //---c:\My Folder\Subdir2---

}

//---print out some info about the directory---

Console.WriteLine(di.FullName);

Console.WriteLine(di.CreationTime);

//---get and print all the subdirectories---

DirectoryInfo[] subDirs = di.GetDirectories();

foreach (DirectoryInfo subDir in subDirs)

Console.WriteLine(subDir.FullName);

//---get the parent of C:\My folder---

DirectoryInfo parent = di.Parent;

if (parent.Exists) {

//---prints out C:\---

Console.WriteLine(parent.FullName);

}

//---creates C:\My Folder\Subdir3---

DirectoryInfo newlyCreatedFolder =

di.CreateSubdirectory("Subdir3");

//---deletes C:\My Folder\Subdir3---

newlyCreatedFolder.Delete();

} catch (IOException ex) {

Console.WriteLine(ex.Message);

} catch (Exception ex) {

Console.WriteLine(ex.Message);

}

Console.ReadLine();

}

In this example, you first create an instance of the DirectoryInfoclass by instantiating it with a path (C:\My Folder). You check if the path exists by using the Existproperty. If it does not exist, you create the folder (C:\My Folder) and then create two subdirectories underneath it (Subdir1 and Subdir2).

Next, you print out the full pathname (using the FullNameproperty) of the folder and its creation date (using the CreationTimeproperty). You then get all the subdirectories under C:\My Folder and display their full pathnames. You can get the parent of the C:\My Folder using the Parentproperty.

Finally, you create a subdirectory named Subdir3 under C:\My Folder and pass a reference to the newly created subdirectory to the newlyCreatedFolderobject. You then delete the folder, using the Delete()method.

Directory Class

The Directoryclass is similar to DirectoryInfoclass. The key difference between is that Directoryexposes static members instead of instance members. The Directoryclass also exposes only methods — no properties. Some of the commonly used methods are described in the following table.

Method Description
CreateDirectory Creates a subdirectory.
Delete Deletes a specified directory.
Exists Indicates if a specified path exists.
GetCurrentDirectory Gets the current working directory.
GetDirectories Gets the subdirectories of the specified path.
GetFiles Gets the file list from a specified directory.
SetCurrentDirectory Sets the current working directory.

Refer to the MSDN documentation for a full list of methods and properties.

Here's the previous program using the DirectoryInfoclass rewritten to use the Directoryclass:

static void Main(string[] args) {

string path = @"C:\My Folder";

try {

//---if directory does not exists---

if (!Directory.Exists(path)) {

//---create the directory---

Directory.CreateDirectory(path);

//---set the current directory to C:\My Folder---

Directory.SetCurrentDirectory(path);

//---creates subdirectories---

//---c:\My Folder\Subdir1---

Directory.CreateDirectory("Subdir1");

//---c:\My Folder\Subdir2---

Directory.CreateDirectory("Subdir2");

}

//---set the current directory to C:\My Folder---

Directory.SetCurrentDirectory(path);

//---print out some info about the directory---

Console.WriteLine(Directory.GetCurrentDirectory());

Console.WriteLine(Directory.GetCreationTime(path));

//---get and print all the subdirectories---

string[] subDirs = Directory.GetDirectories(path);

foreach (string subDir in subDirs)

Console.WriteLine(subDir);

//---get the parent of C:\My folder---

DirectoryInfo parent = Directory.GetParent(path);

if (parent.Exists) {

//---prints out C:\---

Console.WriteLine(parent.FullName);

}

//---creates C:\My Folder\Subdir3---

Directory.CreateDirectory("Subdir3");

//---deletes C:\My Folder\Subdir3---

Directory.Delete("Subdir3");

} catch (IOException ex) {

Console.WriteLine(ex.Message);

} catch (Exception ex) {

Console.WriteLine(ex.Message);

}

Console.ReadLine();

}

As you can see, most of the methods in the Directoryclass require you to specify the directory you are working with. If you like to specify the directory path by using relative path names, you need to set the current working directory using the SetCurrentDirectory()method; if not, the default current directory is always the location of your program. Also, notice that some methods (such as GetParent()) still return DirectoryInfoobjects.

In general, if you are performing a lot of operations with directories, use the DirectoryInfoclass. Once it is instantiated, the object has detailed information about the directory you are currently working on. In contrast, the Directory class is much simpler and is suitable if you are occasionally dealing with directories.

Working with Files Using the File and FileInfo Classes

The .NET Framework class library contains two similar classes for dealing with files — FileInfo andFile.

The Fileclass provides static methods for creating, deleting, and manipulating files, whereas the FileInfoclass exposes instance members for files manipulation.

Like the Directoryclass, the Fileclass only exposes static methods and does not contain any properties.

Consider the following program, which creates, deletes, copies, renames, and sets attributes in files, using the Fileclass:

static void Main(string[] args) {

string filePath = @"C:\temp\textfile.txt";

string fileCopyPath = @"C:\temp\textfile_copy.txt";

string newFileName = @"C:\temp\textfile_newcopy.txt";

try {

//---if file already existed---

if (File.Exists(filePath)) {

//---delete the file---

File.Delete(filePath);

}

//---create the file again---

FileStream fs = File.Create(filePath);

fs.Close();

//---make a copy of the file---

File.Copy(filePath, fileCopyPath);

//--rename the file---

File.Move(fileCopyPath, newFileName);

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x