阅读量:66
在C#脚本中可以通过几种方式调用外部资源,其中常见的方式包括:
- 使用System.Net命名空间中的WebClient类来访问网络资源,例如下载文件或访问Web API。
using System.Net;
WebClient client = new WebClient();
string result = client.DownloadString("http://www.example.com/api/data");
- 使用System.IO命名空间中的FileStream类来读取或写入本地文件。
using System.IO;
string filePath = @"C:\example.txt";
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
// 读取文件内容
}
// 或者写入文件内容
using (FileStream fs = new FileStream(filePath, FileMode.Append))
{
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine("Hello, World!");
}
}
- 使用DllImport特性来调用外部的动态链接库(DLL)。
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern bool MessageBox(IntPtr hWnd, string text, string caption, uint type);
MessageBox(IntPtr.Zero, "Hello, World!", "Message", 0);
- 使用第三方库或API来访问特定的外部资源,例如使用Json.NET库来处理JSON数据。
using Newtonsoft.Json;
string json = "{\"name\":\"John\", \"age\":30}";
dynamic data = JsonConvert.DeserializeObject(json);
string name = data.name;
int age = data.age;