[C#] 纯文本查看 复制代码
using System;
using System.IO;
using System.Net.Http;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Text;
namespace ty
{
public partial class Form1 : Form
{
private readonly HttpClient httpClient = new HttpClient();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
// 获取textBox2中的目录路径
string directoryPath = textBox2.Text;
// 检查目录是否存在并删除小于1KB的TXT文件
ProcessDirectory(directoryPath, 1024, "已经删除小于 1KB 的 TXT.");
}
private void button2_Click_1(object sender, EventArgs e)
{
// 获取textBox2中的目录路径
string directoryPath = textBox2.Text;
// 检查目录是否存在并删除大于5KB的TXT文件
ProcessDirectory(directoryPath, 5120, "已经删除大于 5KB 的 TXT.");
}
private void button3_Click(object sender, EventArgs e)
{
}
private async void button4_Click(object sender, EventArgs e)
{
// 点击后更改button4文本
button4.Text = "正在改写文章中";
button4.Enabled = false;
// 禁用其他按钮
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
string apiKey = textBox1.Text.Trim();
string directoryPath = textBox2.Text;
string iniFilename = "zhiling.ini";
if (!Directory.Exists(directoryPath))
{
textBox3.AppendText("当前目录不存在,请重新检查路径!." + Environment.NewLine);
return;
}
string outputDirectory = Path.Combine(directoryPath, "已改写");
if (!Directory.Exists(outputDirectory))
{
Directory.CreateDirectory(outputDirectory);
}
var txtFiles = Directory.GetFiles(directoryPath, "*.txt");
List<Task> tasks = new List<Task>();
foreach (var txtFile in txtFiles)
{
string content = File.ReadAllText(txtFile, Encoding.UTF8);
string iniContent = ReadIniContent(Path.Combine(directoryPath, iniFilename));
if (iniContent != null)
{
string appendedContent = content + "\n" + iniContent;
tasks.Add(ProcessFileAsync(appendedContent, "qwen-turbo", apiKey, txtFile, outputDirectory));
}
else
{
textBox3.AppendText($"无法读取INI文件内容: {iniFilename}{Environment.NewLine}");
return;
}
}
// 等待所有文件处理完成
await Task.WhenAll(tasks);
// 所有文件处理完毕后恢复按钮状态
button4.Text = "改写文章内容";
button4.Enabled = true;
// 启用其他按钮
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
}
private async Task ProcessFileAsync(string appendedContent, string model, string apiKey, string txtFile, string outputDirectory)
{
try
{
HttpResponseMessage response = await CallApiAsync(appendedContent, model, apiKey);
if (response != null && response.IsSuccessStatusCode)
{
string responseJson = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson);
dynamic responseJsonDynamic = JsonConvert.DeserializeObject<dynamic>(responseJson);
if (responseJson != null)
{
string outputText = responseJsonDynamic.output.text;
// 在这里添加对outputText的空值检查
if (!string.IsNullOrEmpty(outputText))
{
string newFilename = Path.GetFileNameWithoutExtension(txtFile) + ".txt";
string outputPath = Path.Combine(outputDirectory, newFilename);
File.WriteAllText(outputPath, outputText, Encoding.UTF8);
File.Delete(txtFile);
}
else
{
textBox3.Invoke((MethodInvoker)(() =>
{
textBox3.AppendText($"无法从API响应中获取有效内容.{Environment.NewLine}");
}));
}
}
else
{
textBox3.Invoke((MethodInvoker)(() =>
{
textBox3.AppendText($"调用API时发生错误,状态码: {response?.StatusCode}{Environment.NewLine}");
}));
}
}
}
catch (Exception ex)
{
textBox3.Invoke((MethodInvoker)(() =>
{
textBox3.AppendText($"在处理文件 {txtFile} 时发生错误:{ex.Message}{Environment.NewLine}");
}));
}
}
private void ProcessDirectory(string directoryPath, int sizeThreshold, string message)
{
try
{
string[] txtFiles = Directory.GetFiles(directoryPath, "*.txt");
foreach (string filePath in txtFiles)
{
long fileSize = new FileInfo(filePath).Length;
if (sizeThreshold < 0 ? fileSize <= -sizeThreshold : fileSize >= sizeThreshold)
{
File.Delete(filePath);
textBox3.AppendText($"{filePath}{Environment.NewLine}");
}
}
textBox3.AppendText(message + Environment.NewLine);
}
catch (Exception ex)
{
textBox3.AppendText($"An error occurred: {ex.Message}{Environment.NewLine}");
}
}
private string ReadIniContent(string filename)
{
if (File.Exists(filename))
{
using (StreamReader reader = new StreamReader(filename, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
else
{
throw new FileNotFoundException("指定的 INI 文件未找到");
}
}
private async Task<HttpResponseMessage> CallApiAsync(string prompt, string model, string apiKey)
{
var url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
var headers = new Dictionary<string, string>
{
{ "Content-Type", "application/json" },
{ "Authorization", $"Bearer {apiKey}" },
};
var body = new Dictionary<string, object>
{
{ "model", model },
{ "input", new Dictionary<string, string> { { "prompt", prompt } } },
{ "parameters", new Dictionary<string, int> { { "max_tokens", 1500 } } },
};
var jsonBody = JsonConvert.SerializeObject(body);
var httpContent = new StringContent(jsonBody, Encoding.UTF8, "application/json");
return await httpClient.PostAsync(url, httpContent);
}
}
}