How can I upload a file to google drive, with given mail address, using C#?
问题:
回答1:
In addition to @NicoRiff's reference, you may also check this Uploading Files documentation. Here's a sample code:
var fileMetadata = new File()
{
Name = "My Report",
MimeType = "application/vnd.google-apps.spreadsheet"
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/report.csv",
System.IO.FileMode.Open))
{
request = driveService.Files.Create(
fileMetadata, stream, "text/csv");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
You may also check on this tutorial.
回答2:
Not sure what you meant by "upload with mail ID". For accessing a user's Google Drive, you'll have to receive an Access Token from Google for that particular account. This is done using the API.
The Access Token will be returned, upon receiving user's consent. This Access Token is used to send API requests. Learn more about Authorization
For a start, you have to enable your Drive API, register your project and obtain credentials from the Developer Console
You can then use the following code for receiving user's consent and obtaining an authenticated Drive Service
string[] scopes = new string[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile};
var clientId = "xxxxxx"; // From https://console.developers.google.com
var clientSecret = "xxxxxxx"; // From https://console.developers.google.com
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId,
ClientSecret = clientSecret},
scopes,
Environment.UserName,
CancellationToken.None,
new FileDataStore("MyAppsToken")).Result;
//Once consent is received, your token will be stored locally on the AppData directory, so that next time you won't be prompted for consent.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyAppName",
});
service.HttpClient.Timeout = TimeSpan.FromMinutes(100);
//Long Operations like file uploads might timeout. 100 is just precautionary value, can be set to any reasonable value depending on what you use your service for.
Following is a working piece of code for uploading to Drive.
// _service: Valid, authenticated Drive service
// _uploadFile: Full path to the file to upload
// _parent: ID of the parent directory to which the file should be uploaded
public static Google.Apis.Drive.v2.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")
{
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description = _descrp;
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
}
catch(Exception e)
{
MessageBox.Show(e.Message,"Error Occured");
}
}
else
{
MessageBox.Show("The file does not exist.","404");
}
}
Here's the little function for determining a file's MIME Type:
private static string GetMimeType(string fileName)
{
string mimeType = "application/unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();
return mimeType;
}
Source.