В настоящее время я работаю над проектом, который требует от меня чтения и записи данных из листов Google. Поэтому я начал с Краткого руководства по API Google Sheets (v4) а> для C#. Я использую Visual Studio 2017 и имею последние версии всех пакетов nuget.
Я шаг за шагом следовал руководству, но вместо создания консольного приложения я создал приложение Windows Form. Код и другие шаги были выполнены точно так, как написано.
При запуске внутри IDE код работает так, как ожидалось. Однако при публикации и последующем запуске вне среды IDE система не может найти System.Net.HTTP.
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in WindowsFormsApp1.exe
Could not load file or assembly 'System.Net.Http, Version=4.1.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.The system cannot find the file specified.
После изучения и опробования решений, опубликованных в других подобных вопросах (которые не сработали), я попал в сообщение StackOverflow, предлагающее перенаправить старую версию System.Net.Http на последнюю версию. Однако это не сработало.
App.config с кодом перенаправления (скриншот)
Вот мой текущий код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.IO;
using System.Threading;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
static string ApplicationName = "Google Sheets API .NET Quickstart";
public Form1()
{
InitializeComponent();
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define request parameters.
String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
String range = "Class Data!A2:E";
SpreadsheetsResource.ValuesResource.GetRequest request =
service.Spreadsheets.Values.Get(spreadsheetId, range);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
ValueRange response = request.Execute();
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
Console.WriteLine("Name, Major");
foreach (var row in values)
{
// Print columns A and E, which correspond to indices 0 and 4.
Console.WriteLine("{0}, {1}", row[0], row[4]);
}
}
else
{
Console.WriteLine("No data found.");
}
Console.Read();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Любая помощь в устранении этой проблемы будет высоко оценена. Спасибо!