How to get all images from FirebaseStorage in C#? - c#

I want to get all images I have saved in my storage folder. There is a way to get the Metadata and the Downloadlink for only one image. But what if I want the download links for all of my images?
My small code so far:
try
{
FirebaseStorage storage = new FirebaseStorage("*****.appspot.com");
var info = await storage.Child("reports").Child($"{public_id}").Child("report_picture_01.png").GetDownloadUrlAsync();
var starsRef = storage.Child("reports").Child($"{public_id}").Child("report_picture_01.png");
string link = await starsRef.GetDownloadUrlAsync();
MessageBox.Show(info.ToString());
}
catch (FirebaseStorageException ex) { MessageBox.Show(ex.Message); }
Similar questions:
How to get all images stored in firebase storage folder?
Download a file from Firebase using C#
It exist one possible solution: You rename all your image files with numbers and then you ilerate throught your folder and look if theres any files named like the numbers. But is there a smarter and faster way to solve this problem?
I've tried serveral methods for it and it still doesn't work

Related

Downloading images from publicly shared folder on Dropbox

I received a link to shared folder from e-commerce company. The link is public and not shared with my dropbox account directly.
How do I get an url to the image that I can pass to either DownloadAsync method of the same sdk or simply HttpClient and well ... download it?
Ideally it would be the same link I get when I click on the image when viewing that shared folder in a browser.
https://www.dropbox.com/sh/{folder_hash}/{file_hash_maybe}/{filename}?dl=0
This is what I have tried:
using Dropbox.Api;
using Dropbox.Api.Files;
...
var accessToken = "abracadabra";
var sharedFolderUrl = "https://www.dropbox.com/sh/{folder_hash}?dl=0";
using (var dbx = new DropboxClient(accessToken))
{
var sharedLink = new SharedLink(sharedFolderUrl);
var sharedFiles = await dbx.Files.ListFolderAsync(path: "", sharedLink: sharedLink);
// sharedFiles - has over 13,000 entries, I use cursor to get them all.
foreach (var file in sharedFiles.Entries)
{
if (file.IsFile)
{
// tried this, but:
// 1. it's crazy to loop through all
// 2. link.Response.Url gives me the same url to a shared folder for all items
var link = await dbx.Sharing.GetSharedLinkFileAsync(url: sharedFolderUrl, path: "/" + file.Name);
}
}
}
Using the GetSharedLinkFileAsync method is the right way to programmatically download a file from a shared link. It actually gives both the metadata (in the link.Response in your code like you mentioned), as well as the file data directly (not via a URL).
To access the file data, you can use any of the GetContentAs... methods documented under IDownloadResponse as returned by GetSharedLinkFileAsync. In your code, that would look something like: link.GetContentAsStreamAsync() (or whichever one you want).
Alternatively, if you want to download the entire folder from the shared link, you can use the URL parameters documented in this help center article. (That may fail for very large folders though.)

Use uploaded file instead of local file to read content

Im working on a Discord bot and want to create this:
I have a string that reads the content of a local file, but I want to upload that file to a specific website (for example GitHub) and use it, instead of the local file (basically, I want to get rid of the local file and be able to use the uploaded file).
I have this simple line of code:
string[] contentFile = File.ReadAllLines("files/file.txt");
Can somebody help me out here?
Edit: The file contains the lines "1", "2", "3" (and so on), and I want to put these lines in a string array so that I can get access to "1" with contentFile[0], to "2" with contentFile[1] and so on and so forth. It works perfect with a local file, but I do not know how to get access to the uploaded file and the lines within.
So this is how I got it to work (if anyone is interested):
using (var client = new WebClient())
{
client.DownloadFile("www.website.com/file.txt", "files/file.txt");
}
string[] fileContent = File.ReadAllLines("files/file.txt");
while (true)
{
try
{
if (File.Exists("files/file.txt")) File.Delete("files/file.txt");
break;
}
catch (IOException)
{
codeTrue = true;
}
}
This basically downloads the file, reads it and deletes it afterwards. The only "problem" is that everytime I update the file on the website, I need to restart the application, else the string array wont be updated. You can solve that problem by adjusting the code a bit and creating an update-loop.

How to download a public shared file from google drive with C#

I'm trying to download a public shared file from Google Drive using C#.
Here's the code I'm currently using
DriveService.Files.Get(fileId);
Where the fileID is taken from the URL
https://drive.google.com/file/d/{ fileID }/view?usp=sharing
Now this all seems like it should work no problem, but I'm getting a file not found error every time.
I've done this previously with getting a list of files from a public folder that is shared and I managed to get that one working by using this query
ListRequest request = service.Files.List();
request.Q = $"'{ folderID }' in parents";
request.Fields = "files(mimeType,id,modifiedTime,name,version,originalFilename)";
The in parents section is what made this one work, but I can't think of a similar way to make the Get query work, it seems like it should just work if given the right ID and I have the permissions.
I'm definitely logged in correctly, as I'm able to download other files, so I know that's not the problem either.
Any help would be greatly appreciated.
The File Resource returned by request.Execute(); contains a WebContentLink property. It is a link for downloading the content using cookie based authentication. In cases where the content is shared publicly, the content can be downloaded without any credentials.
Or you could just do (in API v2):
var request = MyService.Files.Get(FileID);
var stream = new System.IO.MemoryStream();
try
{
request.Download(stream);
System.IO.FileStream file = new System.IO.FileStream(PathToSave, System.IO.FileMode.Create, System.IO.FileAccess.Write);
Stream.WriteTo(file);
file.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Occured:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
You won't have a downloadlink if the file you are trying to download is a native Google Docs format. If that's the case you must look for the ExportLinks.
You will have several export links, so you will have to choose which format suits you best.
The issue ended up being related to permission scopes when authenticating through GoogleWebAuthorizationBroker.AuthorizeAsync().
I'd played with these previously, and I thought it just didn't work, but it turns out you have to delete any previous credentials for these changes to actually work. See the comments in google's sample.
To read public files I had to add the following permission to my scope
DriveService.Scope.DriveReadonly
Hopefully nobody else will stare at their screen for hours now.

How to download files from OneDrive

I am looking to download my files in public folder from One Drive, but it doesn't download the files.
Here is the scenario:
In public folder I have another folder with multiple files in it and is accessible widely.
for test purpose I have shared all the files in public folder (I don't if it's proper way of sharing it).
The following links are provided for me to download the file:
From shared folder link https://onedrive.live.com/redir?resid=DBBC281099F4FE69!646&authkey=!AGRCGuw8Y2_p9mA&ithint=folder%2c.mp3
From public folder link https://onedrive.live.com/redir?resid=DBBC281099F4FE69%21646
Direct link http://1drv.ms/1z9XlW6 -
I am using BackgroundTransferRequest to download the file using below code:
string filePathToDownload = string.Empty, fileName = "111.mp3";
filePathToDownload = "http://1drv.ms/1z9XlW6";
Uri transferUri = new Uri(Uri.EscapeUriString(filePathToDownload), UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
Uri downloadUri = new Uri(DataSource.TEMPDOWNLOADLOCATION + fileName, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = fileName;
The file is 300Kb, but this only downloads 6 Kb.
How can I directly download the file from the links above (any of them)?
thanks!
If you replace the word redir with download in the url you get the raw file instead of the webpage i.e.
https://onedrive.live.com/download?resid=DBBC281099F4FE69%21646
Basically, you can't. Those links are links to the web content that shows the files you have shared. If your scenario doesn't mind asking the user to log in to OneDrive, then you can use the Live SDK to access these files.
To access your public folder from Live SDK, you need to either use Live SDK to get the folder-id for your public folder, or convert the IDs in the URL you copied into the format the Live SDK uses:
folder.<user-id>.<folder-resid>
Where is the part of before the !. In general you shouldn't construct an ID, since it's possible the IDs will change in the future, and instead you should retrieve the ID from the service. However, with the URL you pasted the ID would be:
folder.DBBC281099F4FE69.DBBC281099F4FE69!646
Which will allow you to call
https://apis.live.net:443/v5.0/folder.DBBC281099F4FE69.DBBC281099F4FE69!646/files?access_token=<valid_token>
and retrieve the IDs for the individual files, which you can then download via Live SDK following these details: http://msdn.microsoft.com/en-US/library/dn659726.aspx#download_a_file
For those who are still looking for a response to that question.
The easiest way to find the file path is to go to One Drive on the web and right-click on the file that we want and select Embed. Ξ€hen on the right we see the info window to integrate our file into a page. Inside the iframe is the source of the file. Then we have to replace the word embed with the word download and that's it.
Try something like this
//we first need the file id
string id = string.Empty;
//we need to get all of the filenames stored in the root of the skydrive account
LiveOperationResult result = await this.client.GetAsync("me/skydrive/files");
//lets make a list of all these filenames
List<object> items = result.Result["data"] as List<object>;
//for every filename, check if it is what we want, in this case "sample.txt"
//if it is what we want, get the id and save it to out already defined id value
foreach (object item in items)
{
IDictionary<string, object> file = item as IDictionary<string, object>;
if (file["name"].ToString() == "sample.txt")
{
id = file["id"].ToString();
}
}
//to download the file we need to use the id + "/content"
LiveDownloadOperationResult result2 = await client.DownloadAsync(string.Format("{0}/content", id));
//once the file had downloaded, lets copy it to IsolatedStorage
Stream stream = result2.Stream;
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileToSave = storage.OpenFile("sample.txt", FileMode.Create, FileAccess.ReadWrite))
{
stream.CopyTo(fileToSave);
stream.Flush();
stream.Close();
}
}
here client is the object of LiveConnectClient class.
Import
using Microsoft.Live;
using Microsoft.Live.Controls;
Here is use txt file as an example. Go through this example:http://www.baileystein.com/2013/10/20/skydrive-how-to-upload-and-download-a-text-file-on-wp8/

Download file and save it in isolated storage

I have following code in my Windows 8/RT app:
public static async Task<StorageFile> SaveAsync(Uri fileUri, StorageFolder folder, string fileName)
{
try
{
var file = await folder.CreateFileAsync(fileName);
var downloader = new BackgroundDownloader();
var download = downloader.CreateDownload(fileUri, file); // here Exeption is fired
var res = await download.StartAsync();
return file;
}
catch (Exception e)
{
Debug.WriteLine(ex.Message);
}
return null;
}
ex.message: Access denied
Note:
file - it's a correct StorageFile (ContentType=image/jpg) fileUri - it's correct image urifolder - it's correct storage folder. What I missed?
What is the value of folder when you call the code? You may need to add a capability in Package.appxmanifest to the appropriate folder (e.g. Pictures folder, Documents folder).
By default, the sandboxed nature of a Modern UI app means that it will have explicit access only to its own local folder (think about it like Isolated Storage). In order to access other locations, your manifest file must declare that it needs to access those other locations. The available locations are, however, quite limited.
If you use the Save File Picker, however, you have access to a larger range of locations in which to save your file.
I found little mistake:I forgot, that fileUri is Uri to local server. Just adding nested property to manifest fixed problem.

Categories

Resources