How to upload file or folder to (shared drive) with google api v3 by c# ?
I tried this but not working, still uploaded in my drive not shared drive
var Folder = new Google.Apis.Drive.v3.Data.File()
{
Name = fName,
MimeType = "application/vnd.google-apps.folder",
DriveId=driveID
};
Google.Apis.Drive.v3.Data.File result = new Google.Apis.Drive.v3.Data.File();
var request = service.Files.Create(Folder);
request.Fields = "name,id,webViewLink";
request.SupportsAllDrives = true;
result = request.Execute();
Console.WriteLine("'" + Folder.Name + "' folder created");
I wrote Parents = new List<string> { driveID }
instead of DriveId=driveID and it worked
Related
I have created a folder on Amazon S3 bucket named as 'test'
using following code
var bucketName = ConfigurationManager.AppSettings["bucketName"].ToString();
var AccessKey = ConfigurationManager.AppSettings["AccessKey"].ToString();
var SecretAccessKey = ConfigurationManager.AppSettings["SecretAccessKey"].ToString();
IAmazonS3 client = new AmazonS3Client(AccessKey, SecretAccessKey, RegionEndpoint.USWest2);
//Create folder with company name
var folderKey = "test"+ "/";
PutObjectRequest request = new PutObjectRequest();
request.BucketName = bucketName;
request.StorageClass = S3StorageClass.Standard;
request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.None;
request.Key = folderKey;
request.ContentBody = string.Empty;
PutObjectResponse response = client.PutObject(request);
Now I want to check whether it is exist there or not..
Found some solution here on link which is in ruby, but i need solution in C#
I would suggest to use AWSSDK.S3 NuGet package. This way you can create a AmazonS3Client and Get a list of buckets by calling var bucketsResponse = await client.ListBucketsAsync() then you can do if (bucketsResponse.Buckets.Any(x => x.BucketName == "test")) to check if your 'test' bucket exists.
I use HigLabo.Net.Dropbox to upload a file to Dropbox. I created a App named synch and I am trying to upload a file. Below is my code
byte[] bytes = System.IO.File.ReadAllBytes(args[1]);
UploadFile(bytes,"sundas.jpg","/Apps/synch/");
public static void UploadFile(byte[] content, string filename, string target)
{
string App_key = "xxxxxxxxxxxxxxx";
string App_secret = "yyyyyyyyyyyyyy";
HigLabo.Net.OAuthClient ocl = null;
HigLabo.Net.AuthorizeInfo ai = null;
ocl = HigLabo.Net.Dropbox.DropboxClient.CreateOAuthClient(App_key, App_secret);
ai = ocl.GetAuthorizeInfo();
string RequestToken= ai.RequestToken;
string RequestTokenSecret= ai.RequestTokenSecret;
string redirect_url = ai.AuthorizeUrl;
AccessTokenInfo t = ocl.GetAccessToken(RequestToken, RequestTokenSecret);
string Token= t.Token;
string TokenSecret= t.TokenSecret;
DropboxClient cl = new DropboxClient(App_key, App_secret, Token, TokenSecret);
HigLabo.Net.Dropbox.UploadFileCommand ul = new HigLabo.Net.Dropbox.UploadFileCommand();
ul.Root = RootFolder.Sandbox;
Console.WriteLine(ul.Root);
ul.FolderPath = target;
ul.FileName = filename;
ul.LoadFileData(content);
Metadata md = cl.UploadFile(ul);
Console.WriteLine("END");
}
The code executes fine but the file is not getting upload in Dropbox.
Am I missing something? Is the path to upload correct? How do I view the file in Dropbox whether it is uploaded or not?
Is there a setting which I am missing while creating the app? I am just looking at the home page and I am expecting the file at the root folder. Am I correct?
Or do I need to look into some other location?
Thanks #smarx and
#Greg.
The below is the code to accomplish the task. Thanks again for your support, I hope this will be helpful for some one.
string filePath="C:\\Tim\\sundar.jpg";
RestClient client = new RestClient("https://api-content.dropbox.com/1/");
IRestRequest request = new RestRequest("files_put/auto/{path}", Method.PUT);
FileInfo fileInfo = new FileInfo(filePath);
long fileLength = fileInfo.Length;
request.AddHeader("Authorization", "Bearer FTXXXXXXXXXXXXXXXXXXXisqFXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
request.AddHeader("Content-Length", fileLength.ToString());
request.AddUrlSegment("path", string.Format("Public/{0}", fileInfo.Name));
byte[] data = File.ReadAllBytes(filePath);
var body = new Parameter
{
Name = "file",
Value = data,
Type = ParameterType.RequestBody,
};
request.Parameters.Add(body);
IRestResponse response = client.Execute(request);
I have a method that checks if my file exists on the drive and if not, it uploads one and adds permission.
This method worked while testing the first time and Update requests worked on the file to.
After deleting all existing files in my drive the upload stopped working, the responsebody is null and if I look at it in viddler the requestbody is also empty.
(the file is a valid docx)
I am using the following code:
DriveService service = Google_SDK.Authentication.AppFlowMetadata.BuildServerDriveService();
Google.Apis.Drive.v2.Data.File file;
var items = service.Files.List().Execute().Items.ToLookup(a => a.OriginalFilename = doc.Name + " (" + doc.Id + ".docx)");
if (items.Count > 0)
{
// This worked while testing:
//string fileId = items.FirstOrDefault().FirstOrDefault().Id;
//FilesResource.UpdateRequest uploadRequest = service.Files.(body, fileId, stream, "application/vnd.google-apps.document");
//uploadRequest.Convert = true;
//uploadRequest.Upload();
file = items.FirstOrDefault().FirstOrDefault();
}
else
{
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
body.Title = doc.Name + " (" + doc.Id + ".docx)";
body.OriginalFilename = doc.Name + " (" + doc.Id + ".docx)";
body.Editable = true;
body.Shared = false;
body.WritersCanShare = false;
body.Copyable = false;
body.Description = doc.Notes;
body.MimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
byte[] byteArray = doc.DocxContent; // valid byteArray
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload uploadRequest = service.Files.Insert(body, stream, "application/vnd.google-apps.document");
uploadRequest.Convert = true;
uploadRequest.Upload();
file = uploadRequest.ResponseBody; // No errors or exceptions but returns null
PermissionsResource.InsertRequest permissionRequest = service.Permissions.Insert(new Permission()
{
Role = "writer",
Type = "user",
EmailAddress = "user#domain.com",
Value = "user#domain.com"
}, file.Id); // file.Id fails becase file equals null
permissionRequest.Execute();
}
I really do not see what I am doing wrong and why this worked the first time.
Thank you in advance.
Edit:
I've been debugging some other parts of my project and I found out that the changes still exist, this seems logical that any deletion is saved as a change for version controll.
Maybe that has something to do with my problems?
Also I forgot to mention that the deletion of all the files is done by code and the drive used is not a gmail account but an *.apps.googleusercontent.com account.
The code I used to remove all the files:
DriveService service = Google_SDK.Authentication.DriveServiceProvider.Service;
FilesResource.ListRequest listRequest = service.Files.List();
FileList listResponse = listRequest.Execute();
int amount = listResponse.Items.Count();
foreach(Google.Apis.Drive.v2.Data.File f in listResponse.Items.AsQueryable()){
FilesResource.DeleteRequest deleteRequest = service.Files.Delete(f.Id);
deleteRequest.Execute();
}
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(String.Format("Removed {0} items.",amount));
return response;
Edit 2:
I've created a completely new document in my system and tried uploading it to the google drive. This was succesfull! After deleting the new document from the drive I got the same behavior as described above, an empty responsebody while uploading.
So even though I removed the old document it still recognizes that it is the same document that used to be on the drive.
Does somebody know a way to prevent this?
I am trying to use the following code to add files to my document library on Sharepoint Office365 using web services.
public void SaveFileToSharePoint(string fileName)
{
try
{
var copyService = new Copy { Url = "https://mydomain.com/_vti_bin/copy.asmx", Credentials = new NetworkCredential("username", "password", "domain") };
var destURL = "https://mydomain.com/Shared%20Documents/" + Path.GetFileName(fileName);
string[] destinationUrl = { destURL };
CopyResult[] cResultArray;
var fFiledInfo = new FieldInformation { DisplayName = "Description", Type = FieldType.Text, Value = Path.GetFileName(fileName) };
FieldInformation[] fFiledInfoArray = {fFiledInfo};
var copyresult = copyService.CopyIntoItems(destURL, destinationUrl, fFiledInfoArray, File.ReadAllBytes(fileName), out cResultArray);
var b = copyresult;
}
catch (Exception ex)
{
}
}
I receive the error "Object Moved". The URL loads the WSDL in the browser though. If there is a better way to upload and get files from SharePoint on Office365 online I would entertain that as well. Thanks.
as the ASMX webservices are deprecated you should check out the "new" rest services of sharepoint. ON MSDN you find information about it
Or you can use the Client object model which would be my favorite way. The following example shows basic usage, to connect to SharePoint online check out the following link
using(ClientContext context = new ClientContext("http://yourURL"))
{
Web web = context.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(#"C:\myfile.txt");
newFile.Url = "file uploaded via client OM.txt";
List docs = web.Lists.GetByTitle("Documents");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
context.ExecuteQuery();
}
Using roqz suggestions above, here is the ultimate solution I came up with to place files in the SharePoint 2013 Office 365 document library and to retrieve them by name:
public void SaveFileToSharePoint(string fileName)
{
using (var context = new ClientContext("https://mydomain.com/"))
{
var passWord = new SecureString();
foreach (var c in "MyPassword") passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("me#mydomain.com", passWord);
var web = context.Web;
var newFile = new FileCreationInformation {Content = File.ReadAllBytes(fileName), Url = Path.GetFileName(fileName)};
var docs = web.Lists.GetByTitle("Documents");
docs.RootFolder.Folders.GetByUrl("Test").Files.Add(newFile);
context.ExecuteQuery();
}
}
public void GetFileFromSharePoint(string fileName, string savePath)
{
using (var context = new ClientContext("https://mydomain.com/"))
{
var passWord = new SecureString();
foreach (var c in "MyPassword") passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("me#mydomain.com", passWord);
var web = context.Web;
var myFile = web.Lists.GetByTitle("Documents").RootFolder.Folders.GetByUrl("Test").Files.GetByUrl(fileName);
context.Load(myFile);
context.ExecuteQuery();
using (var ffl = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, myFile.ServerRelativeUrl))
{
using (var destFile = File.OpenWrite(savePath + fileName))
{
var buffer = new byte[8*1024];
int len;
while ((len = ffl.Stream.Read(buffer, 0, buffer.Length)) > 0)
{
destFile.Write(buffer, 0, len);
}
}
}
}
}
I am uploading or Posting Image to Facebook using Facebook C# SDK but I call this function one time but it uploads the same Image three times or more. It should only upload the Image one time but it does at least three times, I am using 5.4.1 SDK.
Code is:
public void AddCover(string accessToken, string imageName, string folder, string loggedinuserId)
{
FacebookClient facebookClient = new FacebookClient(accessToken);
var fbUpl = new Facebook.FacebookMediaObject
{
FileName = imageName,
ContentType = "image/jpg"
};
var bytes = System.IO.File.ReadAllBytes(#"F:\Websites\Covers\" + folder + "\\" + imageName);
fbUpl.SetValue(bytes);
var photoDetails = new Dictionary<string, object>();
photoDetails.Add("message", "Facebook Covers");
photoDetails.Add("image", fbUpl);
var response = facebookClient.Post(#"/" + loggedinuserId + "/photos", photoDetails);
var result = (IDictionary<string, object>)response;
var postedcoverId = result["id"];
}
Am I missing something here? Please see the code and tell me what I am doing wrong.
Thanks