溫馨提示×

在C#腳本中如何調用外部資源

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

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

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

WebClient client = new WebClient();
string result = client.DownloadString("http://www.example.com/api/data");
  1. 使用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!");
    }
}
  1. 使用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);
  1. 使用第三方庫或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;

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女