Skip to content

Commit 710480e

Browse files
authored
Merge pull request MicrosoftDocs#1093 from msebolt/consolidation-filehandling
consolidation filehandling
2 parents a25ec98 + 3a724b5 commit 710480e

10 files changed

+329
-420
lines changed

.openpublishing.redirection.json

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3855,6 +3855,41 @@
38553855
"redirect_url": "/cpp/dotnet/regular-expressions-cpp-cli#parse_regex",
38563856
"redirect_document_id": false
38573857
},
3858+
{
3859+
"source_path": "docs/dotnet/how-to-enumerate-files-in-a-directory-cpp-cli.md",
3860+
"redirect_url": "/cpp/dotnet/file-handling-and-i-o-cpp-cli#enumerate",
3861+
"redirect_document_id": false
3862+
},
3863+
{
3864+
"source_path": "docs/dotnet/how-to-monitor-file-system-changes-cpp-cli.md",
3865+
"redirect_url": "/cpp/dotnet/file-handling-and-i-o-cpp-cli#monitor",
3866+
"redirect_document_id": false
3867+
},
3868+
{
3869+
"source_path": "docs/dotnet/how-to-read-a-binary-file-cpp-cli.md",
3870+
"redirect_url": "/cpp/dotnet/file-handling-and-i-o-cpp-cli#read_binary",
3871+
"redirect_document_id": false
3872+
},
3873+
{
3874+
"source_path": "docs/dotnet/how-to-read-a-text-file-cpp-cli.md",
3875+
"redirect_url": "/cpp/dotnet/file-handling-and-i-o-cpp-cli#read_text",
3876+
"redirect_document_id": false
3877+
},
3878+
{
3879+
"source_path": "docs/dotnet/how-to-retrieve-file-information-cpp-cli.md",
3880+
"redirect_url": "/cpp/dotnet/file-handling-and-i-o-cpp-cli#retrieve",
3881+
"redirect_document_id": false
3882+
},
3883+
{
3884+
"source_path": "docs/dotnet/how-to-write-a-binary-file-cpp-cli.md",
3885+
"redirect_url": "/cpp/dotnet/file-handling-and-i-o-cpp-cli#write_binary",
3886+
"redirect_document_id": false
3887+
},
3888+
{
3889+
"source_path": "docs/dotnet/how-to-write-a-text-file-cpp-cli.md",
3890+
"redirect_url": "/cpp/dotnet/file-handling-and-i-o-cpp-cli#write_text",
3891+
"redirect_document_id": false
3892+
},
38583893
{
38593894
"source_path": "docs/error-messages/compiler-errors-1/index.md",
38603895
"redirect_url": "/cpp/error-messages/compiler-errors-1/compiler-fatal-errors-c999-through-c1999",

docs/dotnet/TOC.md

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -110,13 +110,6 @@
110110
### [Converting Projects from Mixed Mode to Pure Intermediate Language](converting-projects-from-mixed-mode-to-pure-intermediate-language.md)
111111
## [Regular Expressions (C++/CLI)](regular-expressions-cpp-cli.md)
112112
## [File Handling and I-O (C++/CLI)](file-handling-and-i-o-cpp-cli.md)
113-
### [How to: Enumerate Files in a Directory (C++/CLI)](how-to-enumerate-files-in-a-directory-cpp-cli.md)
114-
### [How to: Monitor File System Changes (C++/CLI)](how-to-monitor-file-system-changes-cpp-cli.md)
115-
### [How to: Read a Binary File (C++/CLI)](how-to-read-a-binary-file-cpp-cli.md)
116-
### [How to: Read a Text File (C++/CLI)](how-to-read-a-text-file-cpp-cli.md)
117-
### [How to: Retrieve File Information (C++/CLI)](how-to-retrieve-file-information-cpp-cli.md)
118-
### [How to: Write a Binary File (C++/CLI)](how-to-write-a-binary-file-cpp-cli.md)
119-
### [How to: Write a Text File (C++/CLI)](how-to-write-a-text-file-cpp-cli.md)
120113
## [Graphics Operations (C++/CLI)](graphics-operations-cpp-cli.md)
121114
### [How to: Convert Image File Formats with the .NET Framework](how-to-convert-image-file-formats-with-the-dotnet-framework.md)
122115
### [How to: Display Images with the .NET Framework](how-to-display-images-with-the-dotnet-framework.md)

docs/dotnet/file-handling-and-i-o-cpp-cli.md

Lines changed: 294 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,33 +5,315 @@ ms.date: "11/04/2016"
55
ms.technology: ["cpp-cli"]
66
ms.topic: "conceptual"
77
dev_langs: ["C++"]
8-
helpviewer_keywords: [".NET Framework [C++], file handling", "files [C++], .NET Framework and", "I/O [C++], .NET Framework applications", ".NET Framework [C++], I/O"]
8+
helpviewer_keywords: [".NET Framework [C++], file handling", "files [C++], .NET Framework and", "I/O [C++], .NET Framework applications", ".NET Framework [C++], I/O",
9+
"files [C++], listing files", "directories [C++], listing files",
10+
"monitoring file system events", "FileSystemWatcher class, examples", "examples [C++], monitoring file system changes", "events [C++], monitoring", "file system events [C++]",
11+
"files [C++], binary", "binary files, reading in C++",
12+
"reading text files", "text files, reading",
13+
"files [C++], retrieving information about", "FileInfo class",
14+
"binary files, writing in C++", "files [C++], binary",
15+
"files [C++], text", "text files, writing in C++"]
916
ms.assetid: 3296fd59-a83a-40d4-bd4a-6096cc13101b
1017
author: "mikeblome"
1118
ms.author: "mblome"
1219
ms.workload: ["cplusplus", "dotnet"]
1320
---
21+
1422
# File Handling and I/O (C++/CLI)
1523
Demonstrates various file operations using the .NET Framework.
1624

1725
The following topics demonstrate the use of classes defined in the <xref:System.IO> namespace to perform various file operations.
1826

19-
## In This Section
27+
## <a name="enumerate"></a> Enumerate Files in a Directory
28+
The following code example demonstrates how to retrieve a list of the files in a directory. Additionally, the subdirectories are enumerated. The following code example uses the <xref:System.IO.Directory.GetFiles%2A><xref:System.IO.Directory.GetFiles%2A> and <xref:System.IO.Directory.GetDirectories%2A> methods to display the contents of the C:\Windows directory.
2029

21-
- [How to: Enumerate Files in a Directory (C++/CLI)](../dotnet/how-to-enumerate-files-in-a-directory-cpp-cli.md)
30+
### Example
2231

23-
- [How to: Monitor File System Changes (C++/CLI)](../dotnet/how-to-monitor-file-system-changes-cpp-cli.md)
32+
```cpp
33+
// enum_files.cpp
34+
// compile with: /clr
35+
using namespace System;
36+
using namespace System::IO;
2437

25-
- [How to: Read a Binary File (C++/CLI)](../dotnet/how-to-read-a-binary-file-cpp-cli.md)
38+
int main()
39+
{
40+
String^ folder = "C:\\";
41+
array<String^>^ dir = Directory::GetDirectories( folder );
42+
Console::WriteLine("--== Directories inside '{0}' ==--", folder);
43+
for (int i=0; i<dir->Length; i++)
44+
Console::WriteLine(dir[i]);
2645

27-
- [How to: Read a Text File (C++/CLI)](../dotnet/how-to-read-a-text-file-cpp-cli.md)
46+
array<String^>^ file = Directory::GetFiles( folder );
47+
Console::WriteLine("--== Files inside '{0}' ==--", folder);
48+
for (int i=0; i<file->Length; i++)
49+
Console::WriteLine(file[i]);
2850

29-
- [How to: Retrieve File Information (C++/CLI)](../dotnet/how-to-retrieve-file-information-cpp-cli.md)
51+
return 0;
52+
}
53+
```
54+
55+
## <a name="monitor"></a> Monitor File System Changes
56+
The following code example uses <xref:System.IO.FileSystemWatcher> to register for events corresponding to files being created, changed, deleted, or renamed. Instead of periodically polling a directory for changes to files, you can use the <xref:System.IO.FileSystemWatcher> class to fire events when a change is detected.
3057
31-
- [How to: Write a Binary File (C++/CLI)](../dotnet/how-to-write-a-binary-file-cpp-cli.md)
58+
### Example
3259
33-
- [How to: Write a Text File (C++/CLI)](../dotnet/how-to-write-a-text-file-cpp-cli.md)
60+
```cpp
61+
// monitor_fs.cpp
62+
// compile with: /clr
63+
#using <system.dll>
3464
35-
36-
## See Also
37-
[.NET Programming with C++/CLI (Visual C++)](../dotnet/dotnet-programming-with-cpp-cli-visual-cpp.md)
65+
using namespace System;
66+
using namespace System::IO;
67+
68+
ref class FSEventHandler
69+
{
70+
public:
71+
void OnChanged (Object^ source, FileSystemEventArgs^ e)
72+
{
73+
Console::WriteLine("File: {0} {1}",
74+
e->FullPath, e->ChangeType);
75+
}
76+
void OnRenamed(Object^ source, RenamedEventArgs^ e)
77+
{
78+
Console::WriteLine("File: {0} renamed to {1}",
79+
e->OldFullPath, e->FullPath);
80+
}
81+
};
82+
83+
int main()
84+
{
85+
array<String^>^ args = Environment::GetCommandLineArgs();
86+
87+
if(args->Length < 2)
88+
{
89+
Console::WriteLine("Usage: Watcher.exe <directory>");
90+
return -1;
91+
}
92+
93+
FileSystemWatcher^ fsWatcher = gcnew FileSystemWatcher( );
94+
fsWatcher->Path = args[1];
95+
fsWatcher->NotifyFilter = static_cast<NotifyFilters>
96+
(NotifyFilters::FileName |
97+
NotifyFilters::Attributes |
98+
NotifyFilters::LastAccess |
99+
NotifyFilters::LastWrite |
100+
NotifyFilters::Security |
101+
NotifyFilters::Size );
102+
103+
FSEventHandler^ handler = gcnew FSEventHandler();
104+
fsWatcher->Changed += gcnew FileSystemEventHandler(
105+
handler, &FSEventHandler::OnChanged);
106+
fsWatcher->Created += gcnew FileSystemEventHandler(
107+
handler, &FSEventHandler::OnChanged);
108+
fsWatcher->Deleted += gcnew FileSystemEventHandler(
109+
handler, &FSEventHandler::OnChanged);
110+
fsWatcher->Renamed += gcnew RenamedEventHandler(
111+
handler, &FSEventHandler::OnRenamed);
112+
113+
fsWatcher->EnableRaisingEvents = true;
114+
115+
Console::WriteLine("Press Enter to quit the sample.");
116+
Console::ReadLine( );
117+
}
118+
```
119+
120+
## <a name="read_binary"></a> Read a Binary File
121+
The following code example shows how to read binary data from a file, by using two classes from the <xref:System.IO?displayProperty=fullName> namespace: <xref:System.IO.FileStream> and <xref:System.IO.BinaryReader>. <xref:System.IO.FileStream> represents the actual file. <xref:System.IO.BinaryReader> provides an interface to the stream that allows binary access.
122+
123+
The code example reads a file that's named data.bin and contains integers in binary format. For information about this kind of file, see [How to: Write a Binary File (C++/CLI)](../dotnet/how-to-write-a-binary-file-cpp-cli.md).
124+
125+
### Example
126+
127+
```cpp
128+
// binary_read.cpp
129+
// compile with: /clr
130+
#using<system.dll>
131+
using namespace System;
132+
using namespace System::IO;
133+
134+
int main()
135+
{
136+
String^ fileName = "data.bin";
137+
try
138+
{
139+
FileStream^ fs = gcnew FileStream(fileName, FileMode::Open);
140+
BinaryReader^ br = gcnew BinaryReader(fs);
141+
142+
Console::WriteLine("contents of {0}:", fileName);
143+
while (br->BaseStream->Position < br->BaseStream->Length)
144+
Console::WriteLine(br->ReadInt32().ToString());
145+
146+
fs->Close( );
147+
}
148+
catch (Exception^ e)
149+
{
150+
if (dynamic_cast<FileNotFoundException^>(e))
151+
Console::WriteLine("File '{0}' not found", fileName);
152+
else
153+
Console::WriteLine("Exception: ({0})", e);
154+
return -1;
155+
}
156+
return 0;
157+
}
158+
```
159+
## <a name="read_text"></a> Read a Text File
160+
The following code example demonstrates how to open and read a text file one line at a time, by using the <xref:System.IO.StreamReader> class that's defined in the <xref:System.IO?displayProperty=fullName> namespace. An instance of this class is used to open a text file and then the <xref:System.IO.StreamReader.ReadLine%2A?displayProperty=fullName> method is used to retrieve each line.
161+
162+
This code example reads a file that's named textfile.txt and contains text. For information about this kind of file, see [How to: Write a Text File (C++/CLI)](../dotnet/how-to-write-a-text-file-cpp-cli.md).
163+
164+
### Example
165+
166+
```cpp
167+
// text_read.cpp
168+
// compile with: /clr
169+
#using<system.dll>
170+
using namespace System;
171+
using namespace System::IO;
172+
173+
int main()
174+
{
175+
String^ fileName = "textfile.txt";
176+
try
177+
{
178+
Console::WriteLine("trying to open file {0}...", fileName);
179+
StreamReader^ din = File::OpenText(fileName);
180+
181+
String^ str;
182+
int count = 0;
183+
while ((str = din->ReadLine()) != nullptr)
184+
{
185+
count++;
186+
Console::WriteLine("line {0}: {1}", count, str );
187+
}
188+
}
189+
catch (Exception^ e)
190+
{
191+
if (dynamic_cast<FileNotFoundException^>(e))
192+
Console::WriteLine("file '{0}' not found", fileName);
193+
else
194+
Console::WriteLine("problem reading file '{0}'", fileName);
195+
}
196+
197+
return 0;
198+
}
199+
```
200+
201+
## <a name="retrieve"></a> Retrieve File Information
202+
The following code example demonstrates the <xref:System.IO.FileInfo> class. When you have the name of a file, you can use this class to retrieve information about the file such as the file size, directory, full name, and date and time of creation and of the last modification.
203+
204+
This code retrieves file information for Notepad.exe.
205+
206+
### Example
207+
208+
```cpp
209+
// file_info.cpp
210+
// compile with: /clr
211+
using namespace System;
212+
using namespace System::IO;
213+
214+
int main()
215+
{
216+
array<String^>^ args = Environment::GetCommandLineArgs();
217+
if (args->Length < 2)
218+
{
219+
Console::WriteLine("\nUSAGE : file_info <filename>\n\n");
220+
return -1;
221+
}
222+
223+
FileInfo^ fi = gcnew FileInfo( args[1] );
224+
225+
Console::WriteLine("file size: {0}", fi->Length );
226+
227+
Console::Write("File creation date: ");
228+
Console::Write(fi->CreationTime.Month.ToString());
229+
Console::Write(".{0}", fi->CreationTime.Day.ToString());
230+
Console::WriteLine(".{0}", fi->CreationTime.Year.ToString());
231+
232+
Console::Write("Last access date: ");
233+
Console::Write(fi->LastAccessTime.Month.ToString());
234+
Console::Write(".{0}", fi->LastAccessTime.Day.ToString());
235+
Console::WriteLine(".{0}", fi->LastAccessTime.Year.ToString());
236+
237+
return 0;
238+
}
239+
```
240+
241+
## <a name="write_binary"></a> Write a Binary File
242+
The following code example demonstrates writing binary data to a file. Two classes from the <xref:System.IO> namespace are used: <xref:System.IO.FileStream> and <xref:System.IO.BinaryWriter>. <xref:System.IO.FileStream> represents the actual file, while <xref:System.IO.BinaryWriter> provides an interface to the stream that allows binary access.
243+
244+
The following code example writes a file containing integers in binary format. This file can be read with the code in [How to: Read a Binary File (C++/CLI)](../dotnet/how-to-read-a-binary-file-cpp-cli.md).
245+
246+
### Example
247+
248+
```cpp
249+
// binary_write.cpp
250+
// compile with: /clr
251+
#using<system.dll>
252+
using namespace System;
253+
using namespace System::IO;
254+
255+
int main()
256+
{
257+
array<Int32>^ data = {1, 2, 3, 10000};
258+
259+
FileStream^ fs = gcnew FileStream("data.bin", FileMode::Create);
260+
BinaryWriter^ w = gcnew BinaryWriter(fs);
261+
262+
try
263+
{
264+
Console::WriteLine("writing data to file:");
265+
for (int i=0; i<data->Length; i++)
266+
{
267+
Console::WriteLine(data[i]);
268+
w->Write(data[i]);
269+
}
270+
}
271+
catch (Exception^)
272+
{
273+
Console::WriteLine("data could not be written");
274+
fs->Close();
275+
return -1;
276+
}
277+
278+
fs->Close();
279+
return 0;
280+
}
281+
```
282+
283+
## <a name="write_text"></a> Write a Text File
284+
The following code example demonstrates how to create a text file and write text to it using the <xref:System.IO.StreamWriter> class, which is defined in the <xref:System.IO> namespace. The <xref:System.IO.StreamWriter> constructor takes the name of the file to be created. If the file exists, it is overwritten (unless you pass True as the second <xref:System.IO.StringWriter> constructor argument).
285+
286+
The file is then filed using the <xref:System.IO.StreamWriter.Write%2A> and <xref:System.IO.TextWriter.WriteLine%2A> functions.
287+
288+
### Example
289+
290+
```cpp
291+
// text_write.cpp
292+
// compile with: /clr
293+
using namespace System;
294+
using namespace System::IO;
295+
296+
int main()
297+
{
298+
String^ fileName = "textfile.txt";
299+
300+
StreamWriter^ sw = gcnew StreamWriter(fileName);
301+
sw->WriteLine("A text file is born!");
302+
sw->Write("You can use WriteLine");
303+
sw->WriteLine("...or just Write");
304+
sw->WriteLine("and do {0} output too.", "formatted");
305+
sw->WriteLine("You can also send non-text objects:");
306+
sw->WriteLine(DateTime::Now);
307+
sw->Close();
308+
Console::WriteLine("a new file ('{0}') has been written", fileName);
309+
310+
return 0;
311+
}
312+
```
313+
314+
## See Also
315+
[.NET Programming with C++/CLI (Visual C++)](../dotnet/dotnet-programming-with-cpp-cli-visual-cpp.md)
316+
317+
[File and Stream I-O](http://msdn.microsoft.com/Library/4f4a33a9-66b7-4cd7-a285-4ad3e4276cd2)
318+
319+
[System.IO namespace](https://msdn.microsoft.com/library/system.io.aspx)

0 commit comments

Comments
 (0)