public IDropboxResult ExecuteTask(IDropboxClient client) { try { var listFolderArg = new ListFolderArg(_path, _recursive, _includeMediaInfo, _includeDeleted); var listFolderResult = client.ListFolderAsync(listFolderArg).Result; return(new DropboxListFolderSuccesResult(listFolderResult)); } catch (Exception exception) { Dev2Logger.Error(exception.Message, GlobalConstants.WarewolfError); var hasInnerExc = exception.InnerException != null; if (hasInnerExc) { if (exception.InnerException.Message.Contains("not_found")) { return(new DropboxFailureResult(new DropboxFileNotFoundException())); } if (exception.InnerException.Message.Contains("malformed")) { return(new DropboxFailureResult(new DropboxFileMalformdedException())); } return(exception.InnerException.Message.Contains("not_file") ? new DropboxFailureResult(new DropboxPathNotFileFoundException()) : new DropboxFailureResult(exception.InnerException)); } return(new DropboxFailureResult(exception)); } }
public static async Task Download()//(string folder, string file) { using (var dbx = new DropboxClient(tk)) { ListFolderArg arg = new ListFolderArg("/txt"); var list = await dbx.Files.ListFolderAsync(arg); // show folders then files foreach (var item in list.Entries) { if (item.IsFolder) { continue; } using (var response = await dbx.Files.DownloadAsync(item.PathLower)) { byte[] bs = await response.GetContentAsByteArrayAsync(); System.IO.FileStream fs = new System.IO.FileStream( string.Format(@"C:\dropbox\{0}", item.Name), System.IO.FileMode.Create, System.IO.FileAccess.Write); //バイト型配列の内容をすべて書き込む fs.Write(bs, 0, bs.Length); //閉じる fs.Close(); //Console.WriteLine(await response.GetContentAsStringAsync()); } } } }
public async Task <ActionResult> UploadFile(FileUploadViewModel model) { List <FileViewModel> resultList = new List <FileViewModel>(); if (ModelState.IsValid) { // Use your file here using (MemoryStream memoryStream = new MemoryStream()) { //model.File.InputStream.CopyTo(memoryStream); using (var dbx = new DropboxClient(accessToken)) { var updated = await dbx.Files.UploadAsync( model.Dir + "/" + model.File.FileName, WriteMode.Overwrite.Instance, body : model.File.InputStream); // body: memoryStream); ListFolderArg arg = new ListFolderArg(model.Dir); var listFolderResult = await dbx.Files.ListFolderAsync(arg); foreach (var item in listFolderResult.Entries.Where(i => i.IsFile)) { resultList.Add(new FileViewModel() { Name = item.Name, Size = item.AsFile.Size, LastUpdate = item.AsFile.ServerModified.ToLongDateString() }); } } } } return(View(resultList)); }
public async Task <string> ForEachAsync(string path, bool recursive, bool deleted, Action <FileItem> action) { const string logstem = "ForEachAsync():{0}"; Action <Metadata> handleEntry = (entry) => { var item = FileItem.Create(entry); if (item.Path != this.context.RemotePath) { action(item); } }; var args0 = new ListFolderArg(path, recursive, false, deleted); ListFolderResult result = await this.Client.Files .ListFolderAsync(args0) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpReadTimeoutInSeconds)); // These logging calls are very expensive so check we're enabled first if (log.IsDebugEnabled) { log.DebugFormat(logstem, "Request:" + Json.ToString(args0)); log.DebugFormat(logstem, "Result:" + Json.ToString(result)); } foreach (var entry in result.Entries) { handleEntry(entry); } while (result.HasMore) { var args1 = new ListFolderContinueArg(result.Cursor); result = await this.Client.Files .ListFolderContinueAsync(args1) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpReadTimeoutInSeconds)); if (log.IsDebugEnabled) { log.DebugFormat(logstem, "Request:" + Json.ToString(args1)); log.DebugFormat(logstem, "Result:" + Json.ToString(result)); } foreach (var entry in result.Entries) { handleEntry(entry); } } return(result.Cursor); }
public override async Task <CloudProviderResponse <List <CloudStorageProviderFileBase> > > ListFiles() { try { Logger.Log(LoggerMessageType.Information | LoggerMessageType.VerboseHigh, "DropboxStorageProvider ListFiles."); List <CloudStorageProviderFileBase> files = new List <CloudStorageProviderFileBase>(); ListFolderArg arg = new ListFolderArg(String.Empty, true); ListFolderResult listFolderResult = await _client.Files.ListFolderAsync(arg); foreach (Metadata curFile in listFolderResult.Entries) { DropboxStorageProviderFile file = DropboxStorageProviderFile.FromMetadata(curFile); if (!file.IsFolder) { if (file.Path.ToLower().EndsWith(".vault")) { files.Add(file); } } } return(new CloudProviderResponse <List <CloudStorageProviderFileBase> >(files)); } catch (AuthException ae) { Logger.Log(LoggerMessageType.Information | LoggerMessageType.VerboseHigh, "An authorisation error occurred whilst attempting to list files from DropboxStorageProvider. {0}", ae.Message); return(new CloudProviderResponse <List <CloudStorageProviderFileBase> >(CloudProviderResponse <List <CloudStorageProviderFileBase> > .Response.AuthenticationError, ae)); } catch (DropboxException de) { Logger.Log(LoggerMessageType.Information | LoggerMessageType.VerboseHigh, "An error occurred whilst attempting to list files from DropboxStorageProvider. {0}", de.Message); if (de.Message.ToLower().Contains("not_found")) { return(new CloudProviderResponse <List <CloudStorageProviderFileBase> >(CloudProviderResponse <List <CloudStorageProviderFileBase> > .Response.NotFound, de)); } else { return(new CloudProviderResponse <List <CloudStorageProviderFileBase> >(CloudProviderResponse <List <CloudStorageProviderFileBase> > .Response.UnknownError, de)); } } catch (Exception ex) { Logger.Log(LoggerMessageType.Information | LoggerMessageType.VerboseHigh, "An unknown error occurred whilst attempting to list files from DropboxStorageProvider. {1}", ex.Message); return(new CloudProviderResponse <List <CloudStorageProviderFileBase> >(CloudProviderResponse <List <CloudStorageProviderFileBase> > .Response.UnknownError, ex)); } }
public override FileItem[] ListFiles(FileItem from) { List <FileItem> mFileItems = new List <FileItem>(); var args = new ListFolderArg(from.Path); var response = DBClient.Files.ListFolderAsync(args); foreach (Metadata item in response.Result.Entries) { if (!item.IsDeleted) { FileItem mFileItem = new FileItem(); mFileItem.Path = item.PathLower; mFileItem.IsDirectory = item.IsFolder; mFileItem.LastModified = item.AsFile.ClientModified.Ticks; mFileItem.Size = (long)item.AsFile.Size; mFileItems.Add(mFileItem); } } if (response.Result.HasMore) { response = DBClient.Files.ListFolderContinueAsync(response.Result.Cursor); foreach (Metadata item in response.Result.Entries) { if (!item.IsDeleted) { FileItem mFileItem = new FileItem(); mFileItem.Path = item.PathLower; mFileItem.IsDirectory = item.IsFolder; mFileItem.LastModified = item.AsFile.ClientModified.Ticks; mFileItem.Size = (long)item.AsFile.Size; mFileItems.Add(mFileItem); } } } return(mFileItems.ToArray()); }
public Task <ListFolderResult> ListFolderAsync(ListFolderArg listFolderArg) { return(_client.Files.ListFolderAsync(listFolderArg)); }
/// <summary> /// <para>Returns the contents of a folder.</para> /// </summary> /// <param name="path">The path to the folder you want to see the contents of.</param> /// <param name="recursive">If true, the list folder operation will be applied /// recursively to all subfolders and the response will contain contents of all /// subfolders.</param> /// <param name="includeMediaInfo">If true, :field:'FileMetadata.media_info' is set for /// photo and video.</param> /// <param name="includeDeleted">If true, the results will include entries for files /// and folders that used to exist but were deleted.</param> /// <returns>The task that represents the asynchronous send operation. The TResult /// parameter contains the response from the server.</returns> /// <exception cref="Dropbox.Api.ApiException{ListFolderError}">Thrown if there is an /// error processing the request; This will contain a <see /// cref="ListFolderError"/>.</exception> public t.Task<ListFolderResult> ListFolderAsync(string path, bool recursive = false, bool includeMediaInfo = false, bool includeDeleted = false) { var listFolderArg = new ListFolderArg(path, recursive, includeMediaInfo, includeDeleted); return this.ListFolderAsync(listFolderArg); }
/// <summary> /// <para>Returns the contents of a folder.</para> /// </summary> /// <param name="listFolderArg">The request parameters</param> /// <returns>The task that represents the asynchronous send operation. The TResult /// parameter contains the response from the server.</returns> /// <exception cref="Dropbox.Api.ApiException{ListFolderError}">Thrown if there is an /// error processing the request; This will contain a <see /// cref="ListFolderError"/>.</exception> public t.Task<ListFolderResult> ListFolderAsync(ListFolderArg listFolderArg) { return this.Transport.SendRpcRequestAsync<ListFolderArg, ListFolderResult, ListFolderError>(listFolderArg, "api", "/files/list_folder", Dropbox.Api.Files.ListFolderArg.Encoder, Dropbox.Api.Files.ListFolderResult.Decoder, Dropbox.Api.Files.ListFolderError.Decoder); }
/// <summary> /// <para>A way to quickly get a cursor for the folder's state. Unlike <see /// cref="Dropbox.Api.Files.Routes.FilesRoutes.ListFolderAsync" />, <see /// cref="Dropbox.Api.Files.Routes.FilesRoutes.ListFolderGetLatestCursorAsync" /> /// doesn't return any entries. This endpoint is for app which only needs to know about /// new files and modifications and doesn't need to know about files that already exist /// in Dropbox.</para> /// </summary> /// <param name="path">The path to the folder you want to see the contents of.</param> /// <param name="recursive">If true, the list folder operation will be applied /// recursively to all subfolders and the response will contain contents of all /// subfolders.</param> /// <param name="includeMediaInfo">If true, :field:'FileMetadata.media_info' is set for /// photo and video.</param> /// <returns>The task that represents the asynchronous send operation. The TResult /// parameter contains the response from the server.</returns> /// <exception cref="Dropbox.Api.ApiException{ListFolderError}">Thrown if there is an /// error processing the request; This will contain a <see /// cref="ListFolderError"/>.</exception> public t.Task<ListFolderGetLatestCursorResult> ListFolderGetLatestCursorAsync(string path, bool recursive = false, bool includeMediaInfo = false) { var listFolderArg = new ListFolderArg(path, recursive, includeMediaInfo); return this.ListFolderGetLatestCursorAsync(listFolderArg); }
/// <summary> /// <para>Returns the contents of a folder.</para> /// <para>NOTE: We're definitely going to streamline this interface.</para> /// </summary> /// <param name="path">The path to the folder you want to see the contents of. May be /// the root (i.e. empty).</param> /// <returns>The task that represents the asynchronous send operation. The TResult /// parameter contains the response from the server.</returns> /// <exception cref="Dropbox.Api.ApiException{ListFolderError}">Thrown if there is an /// error processing the request; This will contain a <see /// cref="ListFolderError"/>.</exception> public t.Task<ListFolderResult> ListFolderAsync(string path) { var listFolderArg = new ListFolderArg(path); return this.ListFolderAsync(listFolderArg); }
/// <summary> /// <para>Returns the contents of a folder.</para> /// <para>NOTE: We're definitely going to streamline this interface.</para> /// </summary> /// <param name="listFolderArg">The request parameters</param> /// <returns>The task that represents the asynchronous send operation. The TResult /// parameter contains the response from the server.</returns> /// <exception cref="Dropbox.Api.ApiException{ListFolderError}">Thrown if there is an /// error processing the request; This will contain a <see /// cref="ListFolderError"/>.</exception> public t.Task<ListFolderResult> ListFolderAsync(ListFolderArg listFolderArg) { return this.Transport.SendRpcRequestAsync<ListFolderArg, ListFolderResult, ListFolderError>(listFolderArg, "api", "/files/list_folder"); }
/// <summary> /// <para>Begins an asynchronous send to the list folder route.</para> /// </summary> /// <param name="path">The path to the folder you want to see the contents of.</param> /// <param name="recursive">If true, list folder operation will be applied recursively /// to all subfolders. And the response will contain contents of all subfolders</param> /// <param name="callback">The method to be called when the asynchronous send is /// completed.</param> /// <param name="callbackState">A user provided object that distinguished this send /// from other send requests.</param> /// <returns>An object that represents the asynchronous send request.</returns> public sys.IAsyncResult BeginListFolder(string path, bool recursive = false, sys.AsyncCallback callback = null, object callbackState = null) { var listFolderArg = new ListFolderArg(path, recursive); return this.BeginListFolder(listFolderArg, callback, callbackState); }
/// <summary> /// <para>Returns the contents of a folder.</para> /// </summary> /// <param name="path">The path to the folder you want to see the contents of.</param> /// <param name="recursive">If true, list folder operation will be applied recursively /// to all subfolders. And the response will contain contents of all subfolders</param> /// <returns>The task that represents the asynchronous send operation. The TResult /// parameter contains the response from the server.</returns> /// <exception cref="Dropbox.Api.ApiException{ListFolderError}">Thrown if there is an /// error processing the request; This will contain a <see /// cref="ListFolderError"/>.</exception> public t.Task<ListFolderResult> ListFolderAsync(string path, bool recursive = false) { var listFolderArg = new ListFolderArg(path, recursive); return this.ListFolderAsync(listFolderArg); }
private async Task <int> Run() { DropboxCertHelper.InitializeCertPinning(); string[] scopeList = new string[] { "files.metadata.read", "files.content.read", "account_info.read", "sharing.read" }; var uid = await AcquireAccessToken(scopeList, IncludeGrantedScopes.None); if (string.IsNullOrEmpty(uid)) { return(1); } // Specify socket level timeout which decides maximum waiting time when no bytes are received by the socket. var httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 }) { // Specify request level timeout which decides maximum time that can be spent on download/upload files. Timeout = TimeSpan.FromMinutes(20) }; try { var config = new DropboxClientConfig("SimpleOAuthApp") { HttpClient = httpClient }; var client = new DropboxClient(Settings.Default.AccessToken, Settings.Default.RefreshToken, Settings.Default.ApiKey, Settings.Default.ApiSecret, config); var scopes = new string[] { "files.metadata.read", "files.content.read", "sharing.read" }; await client.RefreshAccessToken(scopes); if (Settings.Default.SharedLinks == null || Settings.Default.SharedLinks.Count == 0) { Settings.Default.SharedLinks = new System.Collections.Specialized.StringCollection(); Console.Write("Shared link URL: "); var line = Console.ReadLine(); while (line.Length > 0) { Settings.Default.SharedLinks.Add(line); Console.Write("Additional shared link URL (leave blank to finish): "); line = Console.ReadLine(); } Settings.Default.Save(); } var sharedLinks = Settings.Default.SharedLinks; foreach (var sharedLinkUrl in sharedLinks) { GetSharedLinkMetadataArg arg = new GetSharedLinkMetadataArg(sharedLinkUrl); var sharedLinkMetaData = await client.Sharing.GetSharedLinkMetadataAsync(arg); var localDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), sharedLinkMetaData.Name); Directory.CreateDirectory(localDir); Console.WriteLine($"Processing shared link name: {sharedLinkMetaData.Name}"); if (Verbose) { Console.WriteLine($"Shared link local folder: {localDir}"); } SharedLink sharedLink = new SharedLink(sharedLinkUrl); ListFolderArg listFolderArg = new ListFolderArg(path: "", sharedLink: sharedLink); var listFiles = await client.Files.ListFolderAsync(listFolderArg); foreach (var listFile in listFiles.Entries) { try { if (Verbose) { Console.WriteLine($"Processing: {listFile.Name}"); } // Get the remote object details var remoteFile = listFile.AsFile; // Construct a reference to the local equivalent var localFile = Path.Combine(localDir, listFile.Name); if (Verbose) { Console.WriteLine($" Local filename: {localFile}"); } // Do we have a file already if (File.Exists(localFile)) { if (Verbose) { Console.WriteLine($" Local file exists. Comparing timestamp"); } var localTimestamp = File.GetLastWriteTimeUtc(localFile); if (Verbose) { Console.WriteLine($" Checking {remoteFile.ServerModified} with {localTimestamp}"); } if (DateTime.Compare(remoteFile.ServerModified, localTimestamp) == 0) { if (Verbose) { Console.WriteLine($" Skipping unchanged file: {listFile.Name}"); } continue; } } GetSharedLinkMetadataArg downloadArg = new GetSharedLinkMetadataArg(sharedLinkUrl, $"/{listFile.Name}"); if (Verbose) { Console.WriteLine($"SharedLinkUrl: {sharedLinkUrl}"); Console.WriteLine($" File Name: {listFile.Name}"); } var download = await client.Sharing.GetSharedLinkFileAsync(downloadArg); Console.WriteLine($" Downloading: {remoteFile.Name}"); using (var ms = new MemoryStream()) { var bytes = await download.GetContentAsByteArrayAsync(); if (bytes.Length > 0) { File.WriteAllBytes(localFile, bytes.ToArray()); File.SetCreationTimeUtc(localFile, remoteFile.ServerModified); File.SetLastWriteTimeUtc(localFile, remoteFile.ServerModified); } else { Console.Error.WriteLine($"No bytes downloaded"); } } } catch (Exception ex) { Console.Error.WriteLine($"Failed during download: ${ex.Message}"); } } if (Verbose) { Console.WriteLine("Download complete!"); } } if (Verbose) { Console.WriteLine("All downloads complete!"); } if (PromptToExit) { Console.WriteLine("Exit with any key"); Console.ReadKey(); } } catch (HttpException e) { Console.WriteLine("Exception reported from RPC layer"); Console.WriteLine(" Status code: {0}", e.StatusCode); Console.WriteLine(" Message : {0}", e.Message); if (e.RequestUri != null) { Console.WriteLine(" Request uri: {0}", e.RequestUri); } } return(0); }
/// <summary> /// <para>A way to quickly get a cursor for the folder's state. Unlike <see /// cref="Dropbox.Api.Files.Routes.FilesRoutes.ListFolderAsync" />, <see /// cref="Dropbox.Api.Files.Routes.FilesRoutes.ListFolderGetLatestCursorAsync" /> /// doesn't return any entries. This endpoint is for app which only needs to know about /// new files and modifications and doesn't need to know about files that already exist /// in Dropbox.</para> /// </summary> /// <param name="listFolderArg">The request parameters</param> /// <returns>The task that represents the asynchronous send operation. The TResult /// parameter contains the response from the server.</returns> /// <exception cref="Dropbox.Api.ApiException{ListFolderError}">Thrown if there is an /// error processing the request; This will contain a <see /// cref="ListFolderError"/>.</exception> public t.Task<ListFolderGetLatestCursorResult> ListFolderGetLatestCursorAsync(ListFolderArg listFolderArg) { return this.Transport.SendRpcRequestAsync<ListFolderArg, ListFolderGetLatestCursorResult, ListFolderError>(listFolderArg, "api", "/files/list_folder/get_latest_cursor", ListFolderArg.Encoder, ListFolderGetLatestCursorResult.Decoder, ListFolderError.Decoder); }
/// <summary> /// <para>Begins an asynchronous send to the list folder get latest cursor /// route.</para> /// </summary> /// <param name="listFolderArg">The request parameters.</param> /// <param name="callback">The method to be called when the asynchronous send is /// completed.</param> /// <param name="state">A user provided object that distinguished this send from other /// send requests.</param> /// <returns>An object that represents the asynchronous send request.</returns> public sys.IAsyncResult BeginListFolderGetLatestCursor(ListFolderArg listFolderArg, sys.AsyncCallback callback, object state = null) { var task = this.ListFolderGetLatestCursorAsync(listFolderArg); return enc.Util.ToApm(task, callback, state); }
/// <summary> /// <para>Begins an asynchronous send to the list folder route.</para> /// </summary> /// <param name="path">The path to the folder you want to see the contents of. May be /// the root (i.e. empty).</param> /// <param name="callback">The method to be called when the asynchronous send is /// completed.</param> /// <param name="callbackState">A user provided object that distinguished this send /// from other send requests.</param> /// <returns>An object that represents the asynchronous send request.</returns> public sys.IAsyncResult BeginListFolder(string path, sys.AsyncCallback callback, object callbackState = null) { var listFolderArg = new ListFolderArg(path); return this.BeginListFolder(listFolderArg, callback, callbackState); }
/// <summary> /// <para>Begins an asynchronous send to the list folder get latest cursor /// route.</para> /// </summary> /// <param name="path">The path to the folder you want to see the contents of.</param> /// <param name="recursive">If true, the list folder operation will be applied /// recursively to all subfolders and the response will contain contents of all /// subfolders.</param> /// <param name="includeMediaInfo">If true, :field:'FileMetadata.media_info' is set for /// photo and video.</param> /// <param name="callback">The method to be called when the asynchronous send is /// completed.</param> /// <param name="callbackState">A user provided object that distinguished this send /// from other send requests.</param> /// <returns>An object that represents the asynchronous send request.</returns> public sys.IAsyncResult BeginListFolderGetLatestCursor(string path, bool recursive = false, bool includeMediaInfo = false, sys.AsyncCallback callback = null, object callbackState = null) { var listFolderArg = new ListFolderArg(path, recursive, includeMediaInfo); return this.BeginListFolderGetLatestCursor(listFolderArg, callback, callbackState); }
public Task <ListFolderResult> ListFolderAsync(ListFolderArg listFolderArg) => _client.Files.ListFolderAsync(listFolderArg);