Csharp-04

DLL

DLL(Dynamic Link Library)是动态链接库的缩写。它是一种包含可供程序调用的函数和数据的文件。DLL 文件可以包含多个函数,这些函数可以被多个程序调用。DLL 文件的扩展名是 .dll。

创建 DLL

  1. 新建一个类库项目。

  2. 在类库项目中添加类。

  3. 在类库项目中编写类的代码。

  4. 在类库项目中编译代码。

  5. 在类库项目的输出目录中找到编译后的 DLL 文件。

使用 DLL

  1. 在项目中添加引用。

  2. 在项目中使用引用的类。

比如,我需要引用一个 example.dll 文件,我可以在项目中添加引用,然后使用引用的类。

1
2
3
using Example;

...

文件操作

文件读取

1
2
3
4
5
6
7
8
9
10
11
12
using System;
using System.IO;

class Program
{
static void Main()
{
string path = "example.txt";
string content = File.ReadAllText(path);
Console.WriteLine(content);
}
}

文件写入

1
2
3
4
5
6
7
8
9
10
11
12
using System;
using System.IO;

class Program
{
static void Main()
{
string path = "example.txt";
string content = "Hello, World!";
File.WriteAllText(path, content);
}
}

文件追加

1
2
3
4
5
6
7
8
9
10
11
12
using System;
using System.IO;

class Program
{
static void Main()
{
string path = "example.txt";
string content = "Hello, World!";
File.AppendAllText(path, content);
}
}

文件删除

1
2
3
4
5
6
7
8
9
10
11
using System;
using System.IO;

class Program
{
static void Main()
{
string path = "example.txt";
File.Delete(path);
}
}

e.g

编写一个程序,读取一个文件,然后将文件内容倒序写入另一个文件,比如 example.txt 内容为 Hello, World!,则 example-reverse.txt 内容为 !dlroW ,olleH

  1. 创建 example.txt 文件。

  2. 给 example.txt 写入内容为 `Hello, World!

  3. 读取 example.txt 文件。

  4. 将读取的内容打印到控制台。

  5. 将读取的内容倒序写入 example-reverse.txt 文件。

  6. 查看 example-reverse.txt 文件。

  7. 删除 example.txt 和 example-reverse.txt 文件。

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
using System;
using System.IO;

class Program
{
static void Main()
{
string path = "example.txt";
string content = "Hello, World!";
File.WriteAllText(path, content);

string readContent = File.ReadAllText(path);
Console.WriteLine(readContent);

string reverseContent = "";
for (int i = readContent.Length - 1; i >= 0; i--)
{
reverseContent += readContent[i];
}
File.WriteAllText("example-reverse.txt", reverseContent);

File.Delete(path);
File.Delete("example-reverse.txt");
}
}

其他文件操作

文件操作类 File

  • File.Copy 复制文件。

  • File.Move 移动文件。

  • File.Exists 判断文件是否存在。

  • File.GetCreationTime 获取文件创建时间。

  • File.GetLastAccessTime 获取文件最后访问时间。

  • File.GetLastWriteTime 获取文件最后写入时间。

获取文件夹内容可以使用 Directory 类。

  • Directory.GetFiles 获取文件夹中的文件。

  • Directory.GetDirectories 获取文件夹中的文件夹。