1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
using
System;
using
System.IO;
namespace
TestFile
{
class
Program
{
//操作二进制文件简单demo
private
static
string
streamFile =
"stream.data"
;
static
void
Main(
string
[] args)
{
Console.WriteLine(
"开始写文件"
);
using
(BinaryWriter writer =
new
BinaryWriter(File.Open(streamFile, FileMode.Create)))
{
writer.Write(
"hello world!"
);
Console.WriteLine(
"文件写成功"
);
}
using
(BinaryReader br =
new
BinaryReader(File.Open(streamFile, FileMode.Open)))
{
Console.Write(
"文件读出的内容是:"
);
Console.Write(br.ReadString()+
"\n"
);
}
Console.ReadKey();
}
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
using
System;
using
System.IO;
namespace
TestFile
{
class
Program
{
//操作文本文件简单demo
private
static
string
filePath =
@"F:\file.txt"
;
static
void
Main(
string
[] args)
{
Console.WriteLine(
"写数据测试开始"
);
//写数据);
if
(File.Exists(filePath))
//注意using的用法
{
using
(StreamWriter sw = File.CreateText(filePath))
{
sw.Write(
"hello world! my file test"
);
Console.WriteLine(
"写入数据成功"
);
}
}
Console.WriteLine(
"读数据测试开始"
);
//读取文件数据);
if
(File.Exists(filePath))
{
using
(StreamReader sr = File.OpenText(filePath))
{
string
strRead =
string
.Empty;
while
((strRead = sr.ReadLine()) !=
null
)
{
Console.WriteLine(strRead);
}
}
}
try
{
File.Copy(filePath,
@"F:\file1.txt"
);
File.Delete(filePath);
Console.WriteLine(
"删除文件成功"
);
}
catch
(Exception ex)
{
Console.WriteLine(
"删除文件失败:"
+ ex.Message);
}
Console.ReadKey();
}
}
}
|