public void WhenITryToGetListOfAllExistingFiles() { var response = new DropboxApi().GetFilesList(); response.EnsureSuccessful(); ContextHelper.AddToContext("LastApiResponse", response); }
static public Boolean WriteDropbox(String AppKey, String AppSecret, String fileNamePath) { DBFileNamePath = fileNamePath; try { // If the authorizing process has already been started if (DBAuthStart) { // Writes to Dropbox must be a thread. Android reuqirement ThreadPool.QueueUserWorkItem(o => writeDB()); } // If the authorizing process has not been done yet if (!DBAuthStart) { DBAuthStart = true; AppKeyPair appKeys = new AppKeyPair(AppKey, AppSecret); AndroidAuthSession session = new AndroidAuthSession(appKeys); dropboxApi = new DropboxApi(session); (dropboxApi.Session as AndroidAuthSession).StartOAuth2Authentication(MainActivity.mainContext); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("***** WriteDropbox failed: " + e.ToString()); System.Diagnostics.Debug.WriteLine("***** DBAuthStart: " + DBAuthStart); return(false); } return(true); }
public static void addFile(DropboxApi api, DropboxClient client) { string name = ""; string path = ""; Console.WriteLine("Введите полный путь добавляемого файла"); path = Console.ReadLine(); string[] spl = path.Split('\\'); foreach (string s in spl) { if (s.Trim() != "") { name = s; } } Console.WriteLine("Name= " + name); var folder = client.addFile(api, name, path); Console.WriteLine("\t\tФайл добавлен"); Console.WriteLine("{0,20}{1,30}", "Путь ", folder.Root + folder.Path); Console.WriteLine("{0,20}{1,30}", "Изменено ", folder.Modified); }
protected void Button3_Click(object sender, EventArgs e) { Panel1.Visible = true; txtkey.ReadOnly = true; txtpart3.Text = Encrypt(txtpart3.Text); string filename = Session["filename"].ToString(); string FileName = filename + "3_enc.txt"; string enc_part3 = Server.MapPath("~//part3//") + filename + "3_enc.txt"; System.IO.File.WriteAllText(enc_part3, txtpart3.Text); SqlCommand cmd = new SqlCommand("update Tbl_upload set filepath3='" + enc_part3 + "' where filename='" + filename + "'", conn); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); { var accessToken = GetAccessToken2(); var api = new DropboxApi(ConsumerKey2, ConsumerSecret2, accessToken); var file = api.UploadFile("dropbox", FileName, enc_part3); Console.WriteLine(string.Format("{0} uploaded.", file.Path)); Console.WriteLine(); Console.WriteLine("Done. Press any key to continue..."); ClientScript.RegisterStartupScript(Page.GetType(), "Error Message ", "<script language='javascript'>alert(' Upload Successfully')</script>"); } }
private void buttonOK_Click(object sender, EventArgs e) { if (listViewFiles.SelectedItems.Count < 1) { return; } string fileName = listViewFiles.SelectedItems[0].Text; labelInfo.Text = "Downloading..."; this.Refresh(); OAuthToken accessToken = GetSavedToken(); try { Cursor = Cursors.WaitCursor; var api = new DropboxApi(SeConsumerKey, SeConsumerSecret, accessToken); var fileDown = api.DownloadFile("sandbox", fileName); LoadedSubtitle = Encoding.UTF8.GetString(fileDown.Data); Cursor = Cursors.Default; DialogResult = DialogResult.OK; labelInfo.Text = string.Empty; this.Refresh(); } catch (Exception exception) { Cursor = Cursors.Default; MessageBox.Show(exception.Message); } }
public void GivenISendReqestToCreateAFolder() { var response = new DropboxApi().CreateFileFolder("/Test1234Test/Test4"); response.EnsureSuccessful(); ContextHelper.AddToContext("LastApiResponse", response); }
private async void createNeedFolders(DropboxApi api, System.Collections.Specialized.StringCollection buf) { var files = await client.viewFilesAsync(api, ""); bool flag = false; for (int i = 0; i < buf.Count; i++) { string tmp = "/" + buf[i].Split('\\').Last(); foreach (var file in files.Contents) { if (file.Path == tmp) { flag = true; } } if (flag == false) { var fol = await client.createFolderAsync(api, tmp /*"/" + buf[i].Split('\\').Last()*/ /*nameFolder + "/" + name*/); } flag = false; } }
private void buttonOK_Click(object sender, EventArgs e) { var s = textBoxFileName.Text; if (s.Length == 0) { return; } labelInfo.Text = "Saving..."; Refresh(); _oAuth2Token = GetSavedToken(); try { var api = new DropboxApi(SeAppKey, SeAppsecret, _oAuth2Token); var fileUp = api.UploadFile(s, Encoding.UTF8.GetBytes(_rawText)); DialogResult = DialogResult.OK; labelInfo.Text = string.Empty; Refresh(); } catch (Exception exception) { MessageBox.Show(exception.Message); } }
public static void downloadFile(DropboxApi api, DropboxClient client) { string name = ""; string path = ""; Console.WriteLine("Введите название загружаемого файла"); name = Console.ReadLine(); Console.WriteLine("Name= " + name); var folder = client.downloadFile(api, name); string[] spl = name.Split('\\'); foreach (string s in spl) { if (s.Trim() != "") { path = s; } } Console.WriteLine("Name= " + path); folder.Save(path); Console.WriteLine("\t\tФайл добавлен"); Console.WriteLine("{0,20}{1,30}", "Путь ", folder.Root + folder.Path); Console.WriteLine("{0,20}{1,30}", "Изменено ", folder.Modified); }
public static FileListResponseDto GetListOfFilesTest() { var apiResponse = new DropboxApi().GetFilesList(); apiResponse.EnsureSuccessful(); var filesList = apiResponse.Content <FileListResponseDto>(); return(filesList); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); // Creates a new session DBApi = new DropboxApi(CreateSession()); btnLink = FindViewById <Button> (Resource.Id.btnLink); // If you have not specified the keys correctly, disable the link button btnLink.Enabled = VerifyDropboxKeys(); btnClear = FindViewById <Button> (Resource.Id.btnClear); lstImagesName = FindViewById <ListView> (Resource.Id.lstImagesName); // Passes the name and the path of the file that will be downloaded lstImagesName.ItemClick += (sender, e) => { var intent = new Intent(this, typeof(ImageViewActivity)); intent.PutExtra(MainActivity.ImagePathKey, adapter.ImagesPath [e.Position]); intent.PutExtra(MainActivity.ImageNameKey, adapter.ImagesName [e.Position]); StartActivity(intent); }; // Initializes the process of linking to Dropbox or the process to revoke the permission btnLink.Click += delegate { try { if (!DBApi.Session.IsLinked) { (DBApi.Session as AndroidAuthSession).StartOAuth2Authentication(this); } else { Logout(); } } catch (ActivityNotFoundException ex) { Toast.MakeText(this, ex.Message, ToastLength.Long).Show(); } }; // Removes all the downloaded images from Dropbox btnClear.Click += (sender, e) => { try { var files = Directory.GetFiles(CacheDir.AbsolutePath); foreach (var file in files) { File.Delete(file); } Toast.MakeText(this, "All images downloaded from Dropbox have been deleted!", ToastLength.Long).Show(); } catch (System.Exception ex) { Toast.MakeText(this, "There was a problem trying to erase the cache folder: " + ex.Message, ToastLength.Long).Show(); } }; }
static void Main() { // Uncomment the following line or manually provide a valid token so that you // don't have to go through the authorization process each time. var accessToken = GetAccessToken(); //var accessToken = new OAuthToken("token", "secret"); var api = new DropboxApi(ConsumerKey, ConsumerSecret, accessToken); var account = api.GetAccountInfo(); Console.WriteLine(account.DisplayName); Console.WriteLine(account.Email); var total = account.Quota.Total / (1024 * 1024); var used = (account.Quota.Normal + account.Quota.Shared) / (1024 * 1024); Console.WriteLine(String.Format("Dropbox: {0}/{1} Mb used", used, total)); Console.WriteLine(); var publicFolder = api.GetFiles("dropbox", "Public"); foreach (var file in publicFolder.Contents) { Console.WriteLine(file.Path); } // Create a folder var folder = api.CreateFolder("dropbox", "/test"); Console.WriteLine("Folder created."); Console.WriteLine(String.Format("Root: {0}", folder.Root)); Console.WriteLine(String.Format("Path: {0}", folder.Path)); Console.WriteLine(String.Format("Modified: {0}", folder.Modified)); // Move a folder folder = api.Move("dropbox", "/test", "/temp"); // Delete a folder folder = api.Delete("dropbox", "/temp"); // Download a File var fileDownload = api.DownloadFile("dropbox", "Public/YourFileName.ext"); fileDownload.Save(@"D:\YourFileName.ext"); // Upload a File var fileUpload = api.UploadFile("dropbox", "TargetFileName.ext", @"YourFilesLocation"); Console.WriteLine(string.Format("{0} uploaded.", fileUpload.Path)); Console.WriteLine(); Console.WriteLine("Done. Press any key to continue..."); Console.ReadKey(); }
private async void getInfoUser(DropboxApi api) { var account = await client.getInfoAccountAsync(api); diskSpace.Series[0].Points.Clear(); diskSpace.Series[0].Points.AddXY(0, account.Quota.Normal); diskSpace.Series[0].Points[0].LegendText = "Занято " + account.Quota.Normal / 1048576 + " Мб"; diskSpace.Series[0].Points.AddXY(0, account.Quota.Total - account.Quota.Normal); diskSpace.Series[0].Points[1].LegendText = "Свободно " + (account.Quota.Total - account.Quota.Normal) / 1048576 + " Мб"; label1.Text = account.DisplayName; }
private async void moveFileInFolderAsync(DropboxApi api, string folder) { var files = await client.viewFilesAsync(api, ""); foreach (var file in files.Contents) { if (file.Path != "/Синхронизируемая папка") { var obj = await client.moveAsync(api, file.Path, folder + file.Path); } } }
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); SetContentView (Resource.Layout.Main); // Creates a new session DBApi = new DropboxApi (CreateSession ()); btnLink = FindViewById<Button> (Resource.Id.btnLink); // If you have not specified the keys correctly, disable the link button btnLink.Enabled = VerifyDropboxKeys (); btnClear = FindViewById<Button> (Resource.Id.btnClear); lstImagesName = FindViewById<ListView> (Resource.Id.lstImagesName); // Passes the name and the path of the file that will be downloaded lstImagesName.ItemClick += (sender, e) => { var intent = new Intent (this, typeof(ImageViewActivity)); intent.PutExtra (MainActivity.ImagePathKey, adapter.ImagesPath [e.Position]); intent.PutExtra (MainActivity.ImageNameKey, adapter.ImagesName [e.Position]); StartActivity (intent); }; // Initializes the process of linking to Dropbox or the process to revoke the permission btnLink.Click += delegate { try { if (!DBApi.Session.IsLinked) (DBApi.Session as AndroidAuthSession).StartOAuth2Authentication (this); else Logout (); } catch (ActivityNotFoundException ex) { Toast.MakeText (this, ex.Message, ToastLength.Long).Show (); } }; // Removes all the downloaded images from Dropbox btnClear.Click += (sender, e) => { try { var files = Directory.GetFiles (CacheDir.AbsolutePath); foreach (var file in files) File.Delete (file); Toast.MakeText (this, "All images downloaded from Dropbox have been deleted!", ToastLength.Long).Show (); } catch (System.Exception ex) { Toast.MakeText (this, "There was a problem trying to erase the cache folder: " + ex.Message, ToastLength.Long).Show (); } }; }
public static void createNewFolder(DropboxApi api, DropboxClient client) { string name = ""; Console.WriteLine("Введите название папки "); name = Console.ReadLine(); var folder = client.createFolder(api, name); Console.WriteLine("\t\tПапка создана"); Console.WriteLine("{0,20}{1,30}", "Путь ", folder.Root + folder.Path); Console.WriteLine("{0,20}{1,30}", "Изменено ", folder.Modified); }
public static void delete(DropboxApi api, DropboxClient client) { string name = ""; Console.WriteLine("Введите название удаляемого объекта "); name = Console.ReadLine(); var del = client.delete(api, name); Console.WriteLine("\t\tУдалено"); Console.WriteLine("{0,20}{1,30}", "Путь ", del.Root + del.Path); Console.WriteLine("{0,20}{1,30}", "Удалено ", del.Modified); }
public static void getFiles(DropboxApi api, DropboxClient client) { string name = ""; Console.WriteLine("Введите название папки"); name = Console.ReadLine(); var folder = client.viewFiles(api, name); foreach (var file in folder.Contents) { Console.WriteLine(file.Path); } }
static void Main() { Console.WriteLine("{0,45}", "DropBox Client"); line(); DropboxClient client = new DropboxClient(); DropboxApi api = client.connectDropbox("KsHXYcj-h_AAAAAAAAAAUr3Ebnrxv-Hrm8Vn7DYRZ5iEA3pw7xZG5jUs8E2UctRZ"); var account = client.getInfoAccount(api); Console.WriteLine("{0,20}{1}", "Здравствуйте ", account.DisplayName); string command = ""; help(); while (true) { command = Console.ReadLine(); switch (command) { case "VIEW_FILES": getFiles(api, client); break; case "CREATE_FOLDER": createNewFolder(api, client); break; case "DELETE": delete(api, client); break; case "ADD_FILE": addFile(api, client); break; case "DOWNLOAD_FILE": downloadFile(api, client); break; default: Console.WriteLine("Nothing"); break; } } }
protected override void OnStart() { base.OnStart(); AppKeyPair appKeys = new AppKeyPair(AppKey, AppSecret); AndroidAuthSession session = new AndroidAuthSession(appKeys); if (File.Exists(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "/" + "dropboxKey.txt")) { session.OAuth2AccessToken = File.ReadAllText(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "/" + "dropboxKey.txt"); } dropboxApi = new DropboxApi(session); if (!File.Exists(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "/" + "dropboxKey.txt")) { (dropboxApi.Session as AndroidAuthSession).StartOAuth2Authentication(this); } }
public async Task DropboxBadFilesCheck(string bearer, bool fixInvalidFiles) { _api = new DropboxApi(bearer, _token); var currentAccount = await _api.GetCurrentAccount(); var rootNamespaceId = currentAccount?.RootInfo?.RootNamespaceId; _api.SetPathRoot(rootNamespaceId); if (string.IsNullOrEmpty(rootNamespaceId)) { ScanFinished = true; return; } await PerformScan(fixInvalidFiles); ScanFinished = true; }
private void buttonOK_Click(object sender, EventArgs e) { labelInfo.Text = "Saving..."; this.Refresh(); OAuthToken accessToken = GetSavedToken(); try { var api = new DropboxApi(SeConsumerKey, SeConsumerSecret, accessToken); var fileUp = api.UploadFile("sandbox", System.IO.Path.GetFileName(_fileName), Encoding.UTF8.GetBytes(_rawText)); DialogResult = DialogResult.OK; labelInfo.Text = string.Empty; this.Refresh(); } catch (Exception exception) { MessageBox.Show(exception.Message); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); // Creates a new session DBApi = new DropboxApi(CreateSession()); btnLink = FindViewById <Button>(Resource.Id.btnLink); // If you have not specified the keys correctly, disable the link button btnLink.Enabled = VerifyDropboxKeys(); SetDisplay(); UpdateDisplay("Ready"); CreateDirectory(recordFolder); BindUI(); RefreshFiles(); }
private async void getAllFiles(DropboxApi api, string syncFolder, string path) { List <string> tmp = new List <string>(); var files = await client.viewFilesAsync(api, path); foreach (var file in files.Contents) { string syncFile = ""; for (int i = 0; i < file.Path.Split('/').Count(); i++) { if (i != 1 && file.Path.Split('/').ElementAt(i) != "") { syncFile += "\\" + file.Path.Split('/').ElementAt(i); } } string filename = selectedFolder + syncFile; if (isFolder(filename) == false) { if (System.IO.File.Exists(filename) == false) { var folder = await client.downloadFileAsync(api, file.Path.ToString()); watcher.EnableRaisingEvents = false; string nameNewFile = syncFolder + file.Path.ToString().Replace('/', '\\').Substring(path.Length); folder.Save(filename); watcher.EnableRaisingEvents = true; } } else { if (Directory.Exists(filename) == false) { Directory.CreateDirectory(filename); } string root = filename.Substring(syncFolder.Length + 1); getAllFiles(api, syncFolder, path.Replace('\\', '/') + "/" + root.Replace('\\', '/').Split('/').Last()); } } }
private void PluginForm_Shown(object sender, EventArgs e) { Refresh(); _oAuth2token = GetSavedToken(); var api = new DropboxApi(SeAppKey, SeAppsecret, _oAuth2token); if (_oAuth2token == null) { try { Process.Start(api.GetPromptForCodeUrl()); using (var form = new GetDropBoxCode()) { var result = form.ShowDialog(this); if (result == DialogResult.OK && form.Code.Length > 10) { _oAuth2token = api.GetAccessToken(form.Code); } else { MessageBox.Show("Code skipped - no Dropbox :("); return; } } labelInfo.Text = string.Empty; SaveToken(_oAuth2token); } catch (Exception exception) { labelInfo.Text = string.Empty; labelDescription.Text = string.Empty; _connectTries++; if (_connectTries < 2) { PluginForm_Shown(sender, e); return; } MessageBox.Show(exception.Message); buttonOK.Enabled = false; return; } } labelDescription.Text = string.Empty; labelInfo.Text = "Getting file list..."; Cursor = Cursors.WaitCursor; Refresh(); try { _fileList = api.GetFiles(""); Cursor = Cursors.Default; } catch (Exception exception) { Cursor = Cursors.Default; _connectTries++; _connectTries++; if (_connectTries < 2) { PluginForm_Shown(sender, e); return; } MessageBox.Show(exception.Message); buttonOK.Enabled = false; return; } labelInfo.Text = string.Empty; FillListView(); }
private void buttonOK_Click(object sender, EventArgs e) { if (listViewFiles.SelectedItems.Count < 1) { return; } string fileName = listViewFiles.SelectedItems[0].Text; Refresh(); try { Cursor = Cursors.WaitCursor; var f = listViewFiles.SelectedItems[0].Tag as DropboxFile; if (f != null) { var api = new DropboxApi(SeAppKey, SeAppsecret, _oAuth2token); if (f.IsDirectory) { labelInfo.Text = "Getting file list..."; labelDescription.Text = f.Path; Refresh(); _fileList = api.GetFiles(f.Path); if (f.Description == "..") { if (_folder.Count > 0) { var path = _folder.Pop(); var list = _fileList.Contents.ToList(); if (path != string.Empty) { list.Insert(0, new DropboxFile { Path = GetWithoutPart(path), IsDirectory = true, Description = ".." }); } _fileList.Contents = list; } } else { string s = GetWithoutPart(f.Path); _folder.Push(s); var list = _fileList.Contents.ToList(); list.Insert(0, new DropboxFile { Path = s, IsDirectory = true, Description = ".." }); _fileList.Contents = list; } FillListView(); } else { labelInfo.Text = "Downloading..."; Refresh(); var fileDown = api.DownloadFile(listViewFiles.SelectedItems[0].Tag as DropboxFile); LoadedSubtitle = Encoding.UTF8.GetString(fileDown.Data); DialogResult = DialogResult.OK; } Cursor = Cursors.Default; } labelInfo.Text = string.Empty; Refresh(); } catch (Exception exception) { Cursor = Cursors.Default; MessageBox.Show(exception.Message); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_no_nonsense_file_picker); var checkAllowCreateDir = (CheckBox) FindViewById(Resource.Id.checkAllowCreateDir); var checkAllowMultiple = (CheckBox) FindViewById(Resource.Id.checkAllowMultiple); var checkLightTheme = (CheckBox) FindViewById(Resource.Id.checkLightTheme); _textView = (TextView) FindViewById(Resource.Id.text); FindViewById(Resource.Id.button_sd).Click += (s, e) => { Intent i; if (checkLightTheme.Checked) { i = new Intent(this, typeof (FilePickerActivity2)); } else { i = new Intent(this, typeof (FilePickerActivity)); } i.SetAction(Intent.ActionGetContent); i.PutExtra(Const.ExtraAllowMultiple, checkAllowMultiple.Checked); i.PutExtra(Const.ExtraAllowCreateDir, checkAllowCreateDir.Checked); i.PutExtra(Const.ExtraMode, (int) FilePickerMode); StartActivityForResult(i, _codeSd); }; FindViewById(Resource.Id.button_image).Click += (s, e) => { var i = checkLightTheme.Checked ? new Intent(this, typeof (MultimediaPickerActivity2)) : new Intent(this, typeof (MultimediaPickerActivity)); i.SetAction(Intent.ActionGetContent); i.PutExtra(Const.ExtraAllowMultiple, checkAllowMultiple.Checked); i.PutExtra(Const.ExtraAllowCreateDir, checkAllowCreateDir.Checked); i.PutExtra(Const.ExtraMode, (int) FilePickerMode); StartActivityForResult(i, _codeSd); }; FindViewById(Resource.Id.button_ftp).Click += (s, e) => { Intent i; if (checkLightTheme.Checked) { i = new Intent(this, typeof (FtpPickerActivity2)); } else { i = new Intent(this, typeof (FtpPickerActivity)); } i.SetAction(Intent.ActionGetContent); i.PutExtra(Const.ExtraAllowMultiple, checkAllowMultiple.Checked); i.PutExtra(Const.ExtraAllowCreateDir, checkAllowCreateDir.Checked); // What mode is selected (makes no sense to restrict to folders here) var mode = FilePickerMode; i.PutExtra(Const.ExtraMode, (int) mode); StartActivityForResult(i, _codeFtp); }; FindViewById(Resource.Id.button_dropbox).Click += (s, e) => { if (mDBApi == null) { mDBApi = DropboxSyncHelper.GetDBApi(this); } // If not authorized, then ask user for login/permission if (!mDBApi.Session.IsLinked) { ((AndroidAuthSession) mDBApi.Session).StartOAuth2Authentication(this); } else { // User is authorized, open file picker var i = checkLightTheme.Checked ? new Intent(this, typeof (DropboxFilePickerActivity2)) : new Intent(this, typeof (DropboxFilePickerActivity)); i.PutExtra(Const.ExtraAllowMultiple, checkAllowMultiple.Checked); i.PutExtra(Const.ExtraAllowCreateDir, checkAllowCreateDir.Checked); i.PutExtra(Const.ExtraMode, (int) FilePickerMode); StartActivityForResult(i, _codeDb); } }; }
private void PluginForm_Shown(object sender, EventArgs e) { this.Refresh(); OAuthToken accessToken = GetSavedToken(); if (accessToken == null) { try { // Step 1/3: Get request token OAuthToken oauthToken = GetRequestToken(); // Step 2/3: Authorize application var queryString = String.Format("oauth_token={0}", oauthToken.Token); var authorizeUrl = "https://www.dropbox.com/1/oauth/authorize?" + queryString; Process.Start(authorizeUrl); MessageBox.Show("Accept App request from Subtitle Edit - and press OK"); labelInfo.Text = string.Empty; accessToken = GetAccessToken(oauthToken); SaveToken(accessToken.Token, accessToken.Secret); } catch (Exception exception) { labelInfo.Text = string.Empty; labelDescription.Text = string.Empty; _connectTries++; if (_connectTries < 2) { PluginForm_Shown(sender, e); return; } MessageBox.Show(exception.Message); buttonOK.Enabled = false; return; } } labelDescription.Text = string.Empty; labelInfo.Text = "Getting file list..."; Cursor = Cursors.WaitCursor; this.Refresh(); var api = new DropboxApi(SeConsumerKey, SeConsumerSecret, accessToken); try { _fileList = api.GetFiles("sandbox", string.Empty); Cursor = Cursors.Default; } catch (Exception exception) { Cursor = Cursors.Default; _connectTries++; _connectTries++; if (_connectTries < 2) { PluginForm_Shown(sender, e); return; } MessageBox.Show(exception.Message); buttonOK.Enabled = false; return; } labelInfo.Text = string.Empty; foreach (DropboxFile f in _fileList.Contents) { ListViewItem item = new ListViewItem(f.Path); item.SubItems.Add(f.Modified.ToShortDateString() + f.Modified.ToShortTimeString()); item.SubItems.Add(f.Size); listViewFiles.Items.Add(item); } if (listViewFiles.Items.Count > 0) { listViewFiles.Items[0].Selected = true; } }
private async void getStartedSynchronizationAsync(DropboxApi api, string syncFolder, int indexCursor) { updateState(false); string nameSyncFolder = "/" + syncFolder.Split('\\').Last(); string cur = Properties.Settings.Default.cursorsFolders[indexCursor] /*Properties.Settings.Default.cursor*/; Delta delta; if (cur != "") { delta = await api.GetDeltaAsync(cur, nameSyncFolder); } else { delta = await api.GetDeltaAsync(nameSyncFolder); } List <string> newFiles = new List <string>(); //updateExistingFiles(selectedFolder, newFiles ,delta); if (delta.entries.Count() > 0) { delta = await api.GetDeltaAsync(cur, nameSyncFolder /*"/Синхронизируемая папка"*/); cur = delta.cursor; //Properties.Settings.Default.cursor = cur; Properties.Settings.Default.cursorsFolders[indexCursor] = cur; Properties.Settings.Default.Save(); string[] Directories = syncFolder.Split('\\'); foreach (var file in delta.entries) { if (file.Item2 != null) { if (file.Item2.is_dir == false) { string nameFile = Directories.Last(); nameFile = file.Item2.path.Substring(nameFile.Length + 1).Replace('/', '\\'); var folder = await client.downloadFileAsync(api, file.Item2.path.TrimStart('/')); watcher.EnableRaisingEvents = false; folder.Save(syncFolder + nameFile); watcher.EnableRaisingEvents = true; newFiles.Add(syncFolder + nameFile); } else { string nameFolder = Directories.Last(); nameFolder = file.Item2.path.Substring(nameFolder.Length + 1).Replace('/', '\\'); Directory.CreateDirectory(syncFolder + nameFolder); } } else { string nameFile = Directories.Last(); nameFile = file.Item1.Substring(nameFile.Length + 1).Replace('/', '\\'); if (!isFolder(file.Item1.ToString())) { if (System.IO.File.Exists(syncFolder + nameFile)) { watcher.EnableRaisingEvents = false; try { System.IO.File.Delete(syncFolder + nameFile); } catch (Exception e) { } watcher.EnableRaisingEvents = true; } } else { if (System.IO.Directory.Exists(syncFolder + nameFile)) { watcher.EnableRaisingEvents = false; try { System.IO.Directory.Delete(syncFolder + nameFile); } catch (Exception e) { } watcher.EnableRaisingEvents = true; } } } } } uploadNewFiles(syncFolder, newFiles, indexCursor); }
/// <summary> /// Синхронизация с сервера на клиент /// </summary> /// <param name="api">DropboxApi api</param> /// <param name="syncFolder">Синхронизируемая папка. Полный путь</param> private async void synchronizationAsync(DropboxApi api, string syncFolder, int indexCursor) { string cur = Properties.Settings.Default.cursorsFolders[indexCursor] /*Properties.Settings.Default.cursor*/; string nameSyncFolder = "/" + syncFolder.Split('\\').Last(); Delta delta = await api.GetDeltaAsync(cur, nameSyncFolder); cur = delta.cursor; while (true) { LongPollDelta lpDelta = await api.GetLongPollDeltaAsync(cur); if (lpDelta.changes) { updateState(false); delta = await api.GetDeltaAsync(cur, nameSyncFolder); cur = delta.cursor; //Properties.Settings.Default.cursor = cur; Properties.Settings.Default.cursorsFolders[indexCursor] = cur; Properties.Settings.Default.Save(); foreach (var file in delta.entries) { { string[] Directories = syncFolder.Split('\\'); if (file.Item2 != null) { if (file.Item2.is_dir == false) { string nameFile = Directories.Last(); nameFile = file.Item2.path.Substring(nameFile.Length + 1).Replace('/', '\\'); var folder = await client.downloadFileAsync(api, file.Item2.path.TrimStart('/')); watcher.EnableRaisingEvents = false; folder.Save(syncFolder + nameFile); watcher.EnableRaisingEvents = true; } else { string nameFolder = Directories.Last(); nameFolder = file.Item2.path.Substring(nameFolder.Length + 1).Replace('/', '\\'); Directory.CreateDirectory(syncFolder + nameFolder); } } else { string nameFile = Directories.Last(); nameFile = file.Item1.Substring(nameFile.Length + 1).Replace('/', '\\'); if (!isFolder(file.Item1.ToString())) { if (System.IO.File.Exists(syncFolder + nameFile)) { watcher.EnableRaisingEvents = false; try { System.IO.File.Delete(syncFolder + nameFile); } catch (Exception e) { } watcher.EnableRaisingEvents = true; } } else { if (System.IO.Directory.Exists(syncFolder + nameFile)) { watcher.EnableRaisingEvents = false; try { System.IO.Directory.Delete(syncFolder + nameFile); } catch (Exception e) { } watcher.EnableRaisingEvents = true; } } } } } updateState(true); } else { //Properties.Settings.Default.cursor = cur; Properties.Settings.Default.cursorsFolders[indexCursor] = cur; Properties.Settings.Default.Save(); } } }
static void Main(string[] args) { //// Step 1/3: Get request token //OAuthToken oauthToken = GetRequestToken(); //// Step 2/3: Authorize application //var queryString = String.Format("oauth_token={0}", oauthToken.Token); //var authorizeUrl = "https://www.dropbox.com/1/oauth/authorize?" + queryString; //Process.Start(authorizeUrl); //Console.WriteLine("Press any key to continue..."); //Console.ReadKey(); //// Step 3/3: Get access token //OAuthToken accessToken = GetAccessToken(oauthToken); //or use already known tokens: OAuthToken accessToken = new OAuthToken("q12cbpu34360x7s", "bmnb4a6ugpujs74"); Console.WriteLine(String.Format("Your access token: {0}", accessToken.Token)); Console.WriteLine(String.Format("Your access secret: {0}", accessToken.Secret)); var api = new DropboxApi(consumerKey, consumerSecret, accessToken); var fileUp = api.UploadFile("sandbox", "a2.srt", @"D:\Download\a.srt"); Console.WriteLine(string.Format("{0} uploaded.", fileUp.Path)); Console.WriteLine(); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); var publicFolder = api.GetFiles("sandbox", ""); foreach (var f in publicFolder.Contents) { Console.WriteLine(f.Path); } //var x = api.GetFiles("sandbox", "a.srt"); //Console.WriteLine(x.Bytes); //Console.WriteLine(); //Console.WriteLine("Press any key to continue..."); //Console.ReadKey(); var file = api.DownloadFile("sandbox", "a.srt"); var fn = System.IO.Path.GetTempFileName() + ".txt"; file.Save(fn); Process.Start(fn); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
private void PluginForm_Shown(object sender, EventArgs e) { this.Refresh(); OAuthToken accessToken = GetSavedToken(); if (accessToken == null) { try { // Step 1/3: Get request token OAuthToken oauthToken = GetRequestToken(); // Step 2/3: Authorize application var queryString = String.Format("oauth_token={0}", oauthToken.Token); var authorizeUrl = "https://www.dropbox.com/1/oauth/authorize?" + queryString; Process.Start(authorizeUrl); MessageBox.Show("Accept App request from Subtitle Edit - and press OK"); labelInfo.Text = string.Empty; accessToken = GetAccessToken(oauthToken); SaveToken(accessToken.Token, accessToken.Secret); } catch (Exception exception) { _connectTries++; if (_connectTries < 2) { PluginForm_Shown(sender, e); return; } MessageBox.Show(exception.Message); buttonOK.Enabled = false; return; } } labelInfo.Text = "Getting file list..."; this.Refresh(); var api = new DropboxApi(SeConsumerKey, SeConsumerSecret, accessToken); try { Cursor = Cursors.WaitCursor; _fileList = api.GetFiles("sandbox", string.Empty); Cursor = Cursors.Default; } catch (Exception exception) { Cursor = Cursors.Default; _connectTries++; PluginForm_Shown(sender, e); _connectTries++; if (_connectTries < 2) { PluginForm_Shown(sender, e); return; } MessageBox.Show(exception.Message); buttonOK.Enabled = false; return; } labelInfo.Text = string.Empty; MakeDescriptionPrompt(); }