i want to upload a list of .txt, and keep them in a custom folder on skydrive
like Someone's Account -> Skydrive -> custom folder ('testfile')
i have tried
LiveOperationResult res = await client.BackgroundUploadAsync("me/skydrive/testfile", new Uri("/shared/transfers/" + t, UriKind.Relative),OverwriteOption.Overwrite);,
but it doesn't work at all, it give me an error of:
The URL contains the path 'testfile', which isn't supported.
if i need to get folder ID to upload the file, how do i get the ID?
here is my code:
private async void button_Click(object sender, EventArgs e)
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
var temptempout = new List<String>(isoStore.GetFileNames("*").ToList());
int total = temptempout.Count;
int now = 0;
if (temptempout.Count > 0)
{
ShowTextDebug.Text = "Uploaded 0 of " + total + " files";
foreach (String t in temptempout)
{
using (var fileStream = isoStore.OpenFile(t, FileMode.Open, FileAccess.Read))
{
try
{
LiveOperationResult res = await client.BackgroundUploadAsync("me/skydrive/testfile",
new Uri("/shared/transfers/" + t, UriKind.Relative),
OverwriteOption.Overwrite
);
}
catch (Exception err)
{
String rrtt = "there is an error while uploading txt " + err.Message;
MessageBox.Show(rrtt, "error", MessageBoxButton.OK);
}
}
now++;
ShowTextDebug.Text = "Uploaded " + now + " of " + total + " files";
}
ShowTextDebug.Text += "\nupload complete";
}
else
{
MessageBox.Show("no txt exist", "error", MessageBoxButton.OK);
}
}
thanks for helping me
You need to get the folder id first. You can do it as follows:
private async Task<string> GetSkyDriveFolderID(string folderName)
{
client = App.LiveClient;
LiveOperationResult operationResult = await client.GetAsync("me/skydrive/files?filter=folders");
var iEnum = operationResult.Result.Values.GetEnumerator();
iEnum.MoveNext();
var folders = iEnum.Current as IEnumerable;
foreach (dynamic v in folders)
{
if (v.name == folderName)
{
return v.id as string;
}
}
return null;
}
Call this method before uploading the file to get the folder id:
string folderId = await GetSkyDriveFolderId("folderName");
LiveOperationResult res = await client.BackgroundUploadAsync(folderId, new Uri("/shared/transfers/" + t, UriKind.Relative), OverwriteOption.Overwrite);
Related
Using the Google Drive API to upload files. Multiple same console app is running at the same time to upload different parts of files in the folder and their files don't overlap. This hits the quota limit. Then a while-try-catch is implemented to re-execute the query whenever it throws the exception because of the quota limit. The list and create directory method works well but not the upload (i.e. create) method. Some files are missing when i checked from the Google Drive site
Tried using FileStream instead of MemoryStream but it seems not related.
public static Google.Apis.Drive.v3.Data.File uploadFile(DriveService _service, string _uploadFile)
{
bool again = true;
string[] p = _uploadFile.Split('/');
if (System.IO.File.Exists("C:/"+_uploadFile))
{
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
body.Name = System.IO.Path.GetFileName(p[p.Length-1]);
body.Description = "";
body.MimeType = GetMimeType("C:/"+_uploadFile);
body.Parents = new List<string>() { ID };
// File's content.
System.IO.FileStream stream = new System.IO.FileStream("C:/" + _uploadFile, FileMode.Open);
try
{
FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType("C:/" + _uploadFile));
while (again)
{
try
{
request.Upload();
again = false;
}
catch (Exception e)
{
Console.WriteLine("uploadFile: "+p[p.Length-1]);
}
}
return body;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else
{
Console.WriteLine("File does not exist: " + _uploadFile);
return null;
}
}
I am writing on my pdf-word converter and I just received a really strange exception witch makes no sens to me.
Error:PdfiumViewer.PdfException:{"Unsupported security scheme"}
Its the first time that such a exception appears. but I have to be honest that I never tried to convert more then 3-4 files from pdf to word and right now I am doing more then 100 files.
Here is my code I am sry if its too long but I simply do not know on which line the error occurs
public static void PdfToImage()
{
try
{
Application application = null;
application = new Application();
string path = #"C:\Users\chnikos\Desktop\Test\Batch1\";
foreach (string file in Directory.EnumerateFiles(path, "*.pdf"))
{
var doc = application.Documents.Add();
using (var document = PdfiumViewer.PdfDocument.Load(file))
{
int pagecount = document.PageCount;
for (int index = 0; index < pagecount; index++)
{
var image = document.Render(index, 200, 200, true);
image.Save(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png", ImageFormat.Png);
application.Selection.InlineShapes.AddPicture(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png");
}
string getFileName = file.Substring(file.LastIndexOf("\\"));
string getFileWithoutExtras = Regex.Replace(getFileName, #"\\", "");
string getFileWihtoutExtension = Regex.Replace(getFileWithoutExtras, #".pdf", "");
string fileName = #"C:\Users\chnikos\Desktop\Test\Batch1\" + getFileWihtoutExtension;
doc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;
foreach (Microsoft.Office.Interop.Word.InlineShape inline in doc.InlineShapes)
{
.....
}
doc.PageSetup.TopMargin = 28.29f;
doc.PageSetup.LeftMargin = 28.29f;
doc.PageSetup.RightMargin = 30.29f;
doc.PageSetup.BottomMargin = 28.29f;
application.ActiveDocument.SaveAs(fileName, WdSaveFormat.wdFormatDocument);
doc.Close();
string imagePath = #"C:\Users\chnikos\Desktop\Test\Batch1\";
Array.ForEach(Directory.GetFiles(imagePath, "*.png"), delegate(string deletePath) { File.Delete(deletePath); });
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
}
}
}
I am reading around 300 txt files using the task concept. My requirement is to read each file , pick the date from every line , check in which week it comes and then compare it with the folder name which are actually the week names (like 41 , 42) whether they both are same or not. if not then write that file name and the line number. As the number of files and the size of files is huge , I am trying to use task concept to that I can speed up the process. Below is my code.
Any help would be appreciated. Thanks in advance.
private void browse_Click(object sender, EventArgs e)
{
try
{
string newFileName = "";
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
DateTime starttime = DateTime.Now;
string folderPath = Path.GetDirectoryName(folderBrowserDialog1.SelectedPath);
DirectoryInfo dInfo = new DirectoryInfo(folderPath);
string[] Allfiles = Directory.EnumerateFiles(folderPath, "*.txt", SearchOption.AllDirectories).ToArray();
foreach (DirectoryInfo folder in dInfo.GetDirectories())
{
newFileName = "Files_with_duplicate_TGMKT_Names_in_child_Folder_" + folder.Name + ".txt";
if (File.Exists(folderPath + "/" + newFileName))
{
File.Delete(folderPath + "/" + newFileName);
}
FileInfo[] folderFiles = folder.GetFiles();
if (folderFiles.Length != 0)
{
List<Task> tasks = new List<Task>();
foreach (var file in folderFiles)
{
var task = Task.Factory.StartNew(() =>
{
bool taskResult = ReadFile(file.FullName,folderPath,newFileName);
return taskResult;
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
DateTime stoptime = DateTime.Now;
TimeSpan totaltime = stoptime.Subtract(starttime);
label6.Text = Convert.ToString(totaltime);
textBox1.Text = folderPath;
DialogResult result2 = MessageBox.Show("Read the files successfully.", "Important message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
catch (Exception)
{
throw;
}
}
public bool ReadFile(string file , string folderPath , string newFileName)
{
int LineCount = 0;
string fileName = Path.GetFileNameWithoutExtension(file);
using (FileStream fs = File.Open(file, FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
for (int i = 0; i < 2; i++)
{
sr.ReadLine();
}
string oline;
while ((oline = sr.ReadLine()) != null)
{
LineCount = ++LineCount;
string[] eachLine = oline.Split(';');
string date = eachLine[30].Substring(1).Substring(0, 10);
DateTime Date = DateTime.ParseExact(date, "d", CultureInfo.InvariantCulture);
int week = new GregorianCalendar(GregorianCalendarTypes.Localized).GetWeekOfYear(Date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Saturday);
if (Convert.ToString(week) == folderName)
{
}
else
{
using (StreamWriter sw = new StreamWriter(folderPath + "/" + newFileName, true))
{
Filecount = ++Filecount;
sw.WriteLine(fileName + " " + "--" + " " + "Line number :" + " " + LineCount);
}
}
}
}
return true;
}
Your call MessageBox.Show inside ReadFile, which means every file has to write a message. This way you will get 300 messages.
Try to put your message after the WaitAll call outside the ReadFile method.
if (files.Length != 0)
{
List<Task> tasks = new List<Task>();
foreach (var file in files)
{
var task = Task.Factory.StartNew(() =>
{
bool taskResult = ReadFile(file);
return taskResult;
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
// Message here
DialogResult result2 = MessageBox.Show("Read the files successfully.", "Important message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
I am creating the nested folders dynamically for a document library and uploading files. The below code is working fine. but the issues is whenever i uploading the file to the existence folder the ID of the document for the uploaded documents is not in sequence. Suppose if i am uploading a file to path projects\PRJ1\Assignment, fist time it was creating the folders and file with ID's(1\2\3\4) respectively . If i upload other document to the same folder the id of the folders is not changing but the id of the file is 8. i am not unable to find the id 5,6,7 in the document library.
using (CSOM.ClientContext clientContext = new CSOM.ClientContext(SPserverUrl))
{
clientContext.Credentials = new System.Net.NetworkCredential(Username, Password, Domain);
CSOM.Web _Site = clientContext.Web;
// string listrootfolder = "Testlist";
CSOM.List _List = _Site.Lists.GetByTitle("Testlist");
clientContext.Load(_List.RootFolder);
clientContext.ExecuteQuery();
string listrootfolder = _List.RootFolder.Name.ToString();
var folder = CreateFolder(clientContext.Web, "Testlist", folderpath);
// uploading the document
CSOM.FileCreationInformation newFile = new CSOM.FileCreationInformation();
// newFile.Content = System.IO.File.ReadAllBytes(#"D:\Testupload.docx");
byte[] bytes = Convert.FromBase64String(objReqDocumentDetials.FileData.ToString());
newFile.Content = bytes;
// newFile.Url = objDocumentDetials.AttachmentName.ToString() + DateTime.Now.ToString("ddMMyyyyHHmmsss") + "." + objDocumentDetials.FileType.ToString();
newFile.Url = objReqDocumentDetials.FileName.ToString() + "." + objReqDocumentDetials.FileType.ToString();
newFile.Overwrite = true;
Microsoft.SharePoint.Client.File _UploadingFile = folder.Files.Add(newFile);
var item = _UploadingFile.ListItemAllFields;
// var folder = item.GetFolder("account/" + folderName);
// item["Year"] = DateTime.Now.Year.ToString();
// item.Update();
clientContext.Load(_UploadingFile, f => f.ListItemAllFields);
clientContext.ExecuteQuery();
}
public CSOM.Folder CreateFolder(CSOM.Web web, string listTitle, string fullFolderPath)
{
if (string.IsNullOrEmpty(fullFolderPath))
throw new ArgumentNullException("fullFolderPath");
CSOM.List list = web.Lists.GetByTitle(listTitle);
return CreateFolderInternal(web, list.RootFolder, fullFolderPath);
}
public CSOM.Folder CreateFolderInternal(CSOM.Web web, CSOM.Folder parentFolder, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string folderUrl = folderUrls[0];
var curFolder = parentFolder.Folders.Add(folderUrl);
web.Context.Load(curFolder);
web.Context.ExecuteQuery();
if (folderUrls.Length > 1)
{
var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
return CreateFolderInternal(web, curFolder, folderPath);
}
return curFolder;
}
The issue was fixed after redefined the CreateFolder and CreateFolderInternal methods as below
public CSOM.Folder CreateFolder(CSOM.Web web, string listTitle, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
CSOM.List _List = web.Lists.GetByTitle(listTitle);
web.Context.Load(_List.RootFolder);
web.Context.ExecuteQuery();
string listrootfolder = _List.RootFolder.Name.ToString();
web.Context.Load(web, w => w.ServerRelativeUrl);
web.Context.ExecuteQuery();
string root = "";
for (int i = 0; i < folderUrls.Length; i++)
{
root = folderUrls[i].ToString();
string targetFolderUrl = "/" + listrootfolder + "/" + string.Join("/", folderUrls, 0, i + 1);
var folder1 = web.GetFolderByServerRelativeUrl(targetFolderUrl);
web.Context.Load(folder1);
bool exists = false;
try
{
web.Context.ExecuteQuery();
exists = true;
}
catch (Exception ex)
{
}
if (!exists)
{
if (i == 0)
{
CreateFolderInternal(web, _List.RootFolder, root);
}
else
{
web.Context.Load(web, w => w.ServerRelativeUrl);
web.Context.ExecuteQuery();
var targetfolderUrls = targetFolderUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string jj = string.Join("/", targetfolderUrls, 0, targetfolderUrls.Length - 1);
CSOM.Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + jj);
web.Context.Load(folder);
web.Context.ExecuteQuery();
SPCreateFolderInternal(web, folder, root);
}
}
else
{
//already folder exists
}
}
CSOM.Folder finalfolder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + listrootfolder + "/" + fullFolderPath);
web.Context.Load(finalfolder);
web.Context.ExecuteQuery();
return finalfolder;
}
private void CreateFolderInternal(CSOM.Web web, CSOM.Folder parentFolder, string fullFolderPath)
{
try
{
var curFolder = parentFolder.Folders.Add(fullFolderPath);
web.Context.Load(curFolder);
web.Context.ExecuteQuery();
}
catch (System.Exception ex)
{
}
}
When I retrieve all Files (and Folders) of my GoogleDrive Account I should get something like 1500 List elements back, but I get a bit more than 3000 back. I looked into the List and found that some files are 2-3 times in it. Why is that?
Here is the code I use to retrieve the files:
public async Task<List<File>> RetrieveAllFilesAsList(DriveService service, string query = null)
{
List<File> result = new List<File>();
FilesResource.ListRequest request = service.Files.List();
if (query != null)
{
request.Q = query;
}
do
{
try
{
FileList files = await request.ExecuteAsync();
result.AddRange(files.Items);
request.PageToken = files.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred (from RetrieveAllFilesAsList): " + e.Message);
request.PageToken = null;
}
}
while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
Update1:
public async Task<List<File>> RetrieveAllFilesAsList(DriveService service, string query = null)
{
List<File> result = new List<File>();
FilesResource.ListRequest request = service.Files.List();
request.MaxResults = 1000;
if (query != null)
{
request.Q = query + " AND trashed=false";
}
else
{
request.Q = "trashed=false";
}
do
{
try
{
FileList files = await request.ExecuteAsync();
result.AddRange(files.Items);
request.PageToken = files.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred (from RetrieveAllFilesAsList): " + e.Message);
request.PageToken = null;
}
}
while (!String.IsNullOrEmpty(request.PageToken));
int i;
for (i = 0; i < result.Count; i++ )
{
System.IO.File.AppendAllText(#"C:\Users\carl\Desktop\log.txt", result[i].Id + "\t" + result[i].Title + "\t" + result[i].ExplicitlyTrashed.ToString() + "\r\n");
}
// prints 3120 Lines
System.IO.File.AppendAllText(#"C:\Users\carl\Desktop\log.txt", "" + i + Environment.NewLine);
//Count = 3120
System.IO.File.AppendAllText(#"C:\Users\carl\Desktop\log.txt", "" + result.Count);
return result;
}
Word failed to give me the right the linecount, so I did it over my Function.
But I can find the FileId 2-3 times in the File.
I cannot write on the comments yet, so according to the API
from google
"Note: This method returns all files by default. This includes files with trashed=true in the results. Use the trashed=false query parameter to filter these from the results."
So can you check what url of the rest api is actually being called? It seems you need to put some filters on the List method.