溫馨提示×

在C#腳本中如何調(diào)用外部資源

c#
小樊
83
2024-08-19 15:26:31
欄目: 編程語言

在C#腳本中可以通過幾種方式調(diào)用外部資源,其中常見的方式包括:

  1. 使用System.Net命名空間中的WebClient類來訪問網(wǎng)絡(luò)資源,例如下載文件或訪問Web API。
using System.Net;

WebClient client = new WebClient();
string result = client.DownloadString("http://www.example.com/api/data");
  1. 使用System.IO命名空間中的FileStream類來讀取或?qū)懭氡镜匚募?/li>
using System.IO;

string filePath = @"C:\example.txt";
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
    // 讀取文件內(nèi)容
}

// 或者寫入文件內(nèi)容
using (FileStream fs = new FileStream(filePath, FileMode.Append))
{
    using (StreamWriter writer = new StreamWriter(fs))
    {
        writer.WriteLine("Hello, World!");
    }
}
  1. 使用DllImport特性來調(diào)用外部的動態(tài)鏈接庫(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);
  1. 使用第三方庫或API來訪問特定的外部資源,例如使用Json.NET庫來處理JSON數(shù)據(jù)。
using Newtonsoft.Json;

string json = "{\"name\":\"John\", \"age\":30}";
dynamic data = JsonConvert.DeserializeObject(json);
string name = data.name;
int age = data.age;

0