添加检测文件是否存在 相关验证
时间: 2024-03-20 10:45:09 浏览: 13
好的,以下是添加文件是否存在验证的示例代码:
```csharp
using RestSharp;
using System;
using System.IO;
public class FileUploader
{
private readonly string _url;
private readonly string _filePath;
public FileUploader(string url, string filePath)
{
if (!File.Exists(filePath))
{
throw new ArgumentException("文件不存在!", nameof(filePath));
}
_url = url;
_filePath = filePath;
}
public bool Upload()
{
var client = new RestClient(_url);
var request = new RestRequest("upload", Method.POST);
request.AddFile("file", _filePath);
var response = client.Execute(request);
if (response.IsSuccessful)
{
Console.WriteLine("上传成功!");
// 删除本地文件
File.Delete(_filePath);
return true;
}
else
{
Console.WriteLine("上传失败:{0}", response.ErrorMessage);
return false;
}
}
}
```
在构造函数中,我们添加了文件是否存在的判断,并在文件不存在时抛出了 `ArgumentException` 异常。在上传前,我们需要确保文件存在,否则上传会失败。调用示例代码如下:
```csharp
try
{
var uploader = new FileUploader("https://www.example.com", "/path/to/file");
if (uploader.Upload())
{
Console.WriteLine("上传成功!");
}
else
{
Console.WriteLine("上传失败!");
}
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
```
在调用构造函数时,我们需要使用 `try-catch` 语句捕获 `ArgumentException` 异常,以便及时处理文件不存在的情况。