Exception when listing created sub-directory in documents directory - file-io

I am using the official API to list a directory I had created for some purpose and have pushed few files into it. Now I want to list them out.
Here's how I am creating first
final Directory extDir = await getApplicationDocumentsDirectory();
// final String dirPath = '${extDir.path}/Movies/flutter_test';
final String dirPath = '${extDir.path}/mydir';
await new Directory(dirPath).create(recursive: true);
Here's what I am doing to read in a different page.
final Directory extDir = await getApplicationDocumentsDirectory();
// final String dirPath = '${extDir.path}/Pictures/flutter_test';
final String dirPath = '${extDir.path}/mydir';
final String thumbDirPath = '$dirPath/thumbs';
final Directory imgDir = Directory.fromUri(Uri.file(dirPath));
dirExists = imgDir.existsSync();
fileCount = 0;
if(dirExists) {
print("my dir exists");
// thumbDir.list(recursive: false, followLinks: false)
fileCount = await imgDir.list(recursive: false).length;
print('mydir images count $fileCount');
if(fileCount > 1) { // we think one is always the directory itself?
try {
imgDir.list(recursive: false, followLinks: false)
.listen((FileSystemEntity entity) {
The code breaks here giving the following exception message
type '() => Null' is not a subtype of type '(Object) => FutureOr<dynamic>'
I have to also tell you this doesn't happen when I am listing the external storage directory. Am I doing something wrong while creating my directory?
EDIT
I have now upgraded flutter to 0.7.3 on my Mac, and have a new problem altogether. The application won't run at all.

Okay, I found a solution myself. Apparently tinkering with the large provider API has given me different way to list the items, which actually told me I was trying to run listeners twice.
fileCount = await imgDir.list(recursive: false).length;
and
imgDir.list(recursive: false, followLinks: false)
.listen((FileSystemEntity entity) {
from original code cannot be written one after the other, as the first one finishes the listener. This I found out by altering my own code and listing directories this way instead.
Stream<FileSystemEntity> files = imgDir.list(recursive: false, followLinks: false);
will add as many events as many files according to API.. and then create a regular generic list
List<FileSystemEntity> entities = await files.toList();
and then you perform usual iteration using iterator or for() loop like
for(FileSystemEntity entity in entities) {
... // every file now is available

Related

non-invocable member 'File' cannot be used like a method error message- what am I missing?

I have a Blazor Application which had files uploaded to a upload folder on the web server. I am in the process of trying to figure out the code to download an uploaded file in the browser for retrieval and viewing. Right now the code is as below (the download part from code examples on the internet)
public void FileDetailsToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
string path = null;
string uploads = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot\\uploads");
path = uploads + "\\" + SelectedFileName;
if (args.Item.Text == "Delete")
{
//Code for Deleting goes here
//UploadRef.Remove();
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
FileDetailsService.FileDetailsDelete(SelectedFileId); //NavigationManager.NavigateTo($"/ServiceRequestNotes/servicerequestnoteadd");
NavigationManager.NavigateTo($"/ServiceRequests/serviceRequestsaddedit2/{Id}", forceLoad: true);
}
else
{
// its a download
IFileProvider provider = new PhysicalFileProvider(uploads);
IFileInfo fileinfo = provider.GetFileInfo(path + SelectedFileName);
var readStream = fileinfo.CreateReadStream();
var mimeType = "application/pdf";
return File(readStream, mimeType, SelectedFileName);
}
}
On the last statement I am a getting the following error message
non-invocable member 'File' cannot be used like a method error message
What am I missing or do I need to change or add to have the output from the readstream render to the browser?
The blazor application is a blazor server app not WASM. It does not make use of API controllers.
Any advice?
This is a void method. You can't return anything at all. Also, if you're trying to instantiate a File object, you'd have to use the new keyword.

ASP.net - Uploading Files Associated with a Database Record?

I know that there are tons of examples of multi-part form data uploading in ASP.net. However, all of them just upload files to the server, and use System.IO to write it to server disk space. Also, the client side implementations seem to handle files only in uploading, so I can't really use existing upload plugins.
What if I have an existing record and I want to upload images and associate them with the record? Would I need to write database access code in the upload (Api) function, and if so, how do I pass that record's PK with the upload request? Do I instead upload the files in that one request, obtain the file names generated by the server, and then make separate API calls to associate the files with the record?
While at it, does anyone know how YouTube uploading works? From a user's perspective, it seems like we can upload a video, and while uploading, we can set title, description, tags, etc, and even save the record. Is a record for the video immediately created before the API request to upload, which is why we can save info even before upload completes?
Again, I'm not asking HOW to upload files. I'm asking how to associate uploaded files with an existing record and the API calls involved in it. Also, I am asking for what API calls to make WHEN in the user experience when they also input information about what they're uploading.
I'm assuming you're using an api call to get the initial data for displaying a list of files or an individual file. You would have to do this in order to pass the id back to the PUT method to update the file.
Here's a sample of the GET method:
[HttpGet]
public IEnumerable<FileMetaData> Get()
{
var allFiles = MyEntities.Files.Select(f => new FileMetaData()
{
Name = f.Name,
FileName = f.FileName,
Description = f.Description,
FileId = f.Id,
ContentType = f.ContentType,
Tags = f.Tags,
NumberOfKB = f.NumberOfKB
});
return allFiles;
}
Here's a sample of the POST method, which you can adapt to be a PUT (update) instead:
[HttpPost]
[ValidateMimeMultipartContentFilter]
public async Task<IHttpActionResult> PutFile()
{
try
{
var streamProvider =
await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());
//We only allow one file
var thisFile = files[0];
//For a PUT version, you would grab the file from the database based on the id included in the form data, instead of creating a new file
var file = new File()
{
FileName = thisFile.FileName,
ContentType = thisFile.ContentType,
NumberOfKB = thisFile.ContentLength
};
//This is the file metadata that your client would pass in as formData on the PUT / POST.
var formData = streamProvider.FormData;
if (formData != null && formData.Count > 0)
{
file.Id = formData["id"];
file.Description = formData["description"];
file.Name = formData["name"] ?? string.Empty;
file.Tags = formData["tags"];
}
file.Resource = thisFile.Data;
//For your PUT, change this to an update.
MyEntities.Entry(file).State = EntityState.Detached;
MyEntities.Files.Add(file);
await MyEntities.SaveChangesAsync();
//return the ID
return Ok(file.Id.ToString());
}
I got the InMemoryMultipartFormDataStreamProvider from this article:
https://conficient.wordpress.com/2013/07/22/async-file-uploads-with-mvc-webapi-and-bootstrap/
And adapted it to fit my needs for the form data I was returning.

Restore trashed google drive files to a target folder

I need to move all files presently in my google drive's trash to a certain folder or, if that can't be done, restore them to their original location. Some mess happened and I have valuable files in the trash, some 6 gig of them, so I'd prefer to move them to a separate directory, back it up or sync locally and see those files later.
This is the script I have so far:
function moveFilesFromTrash() {
var pageSize = 200;
var files = null;
var token = null;
var cestisti = DocsList.getFolder('cestisti');
do {
var result = DocsList.getAllFilesForPaging(pageSize, token);
files = result.getFiles();
token = result.getToken();
for (var i = 0; i < files.length; i++) {
if (files[i].isTrashed == true) {
Logger.log(files[i].getName());
// files[i].setTrashed(false)
files[i].addToFolder(cestisti);
}
} while (files.length == pageSize);
}
The matter is it just does not work.
The part of the code to page through files items works, I got it from other working scripts of mine. I just don't know if it parses the trash folder or label to. I do not know if setTrashed() or addtofolder() works - I have no idea. Now the former is commented out because I would prefer to copy items instead of restoring them, but if that's not possible I can restore.
This answer has been updated due to the deprecation of DocsList, and now uses DriveApp methods throughout.
You must un-trash a file before you can move it, but doing so will accomplish what you're after. Here's the algorithm:
Get a list of files (or file ids) for all trashed files
For each file,
Undelete / un-trash the file
Move file to target folder (detail: remove file from original folders, add to target recovery folder)
This answer provides snippets of script to accomplish this; The full script is available as a Google Sheets Add-on in a gist, complete with menu and UI elements.
Recover all trashed files
This function uses DriveApp.search() to get the list of all trashed files, and then recovers them into a specified folder, rescueFldr, which will be created if not already there.
/**
* Untrash then move all trashed files to rescue folder.
* From: http://stackoverflow.com/a/14541247/1677912
*
* #returns {Number} Count of Rescued files.
*/
function rescueAllFiles() {
// Find or create target folder
var rescueFldrIterator = DriveApp.getFoldersByName(rescueFldrName);
var rescueFldr = rescueFldrIterator.hasNext() ? rescueFldrIterator.next() : DriveApp.createFolder(rescueFldrName);
// Get file iterator with all trashed files
var trashed = DriveApp.searchFiles('trashed=true');
var count = 0;
while (trashed.hasNext()) {
var file = trashed.next();
// Untrash the file
if (rescueFile( file, rescueFldr )) count++;
}
return(count);
};
Recover specific Trashed Files
If you want to have more control over the files that will be recovered, and you can't simply modify the search parameters used above, an alternative might be to list the file IDs in a spreadsheet, and have a script use that as its input.
Fill spreadsheet with trashed files
/**
* Get array of files in user's Google Drive trash, and write
* into currently active sheet.
* From: http://stackoverflow.com/a/14541247/1677912
*
* #returns {Object[]} Array of DriveApp file objects
*/
function getTrashedFiles() {
var trashedSearch = DriveApp.searchFiles('trashed=true');
var files = [];
files.push(["ID","File Name","Type","URL"]);
while (trashedSearch.hasNext()) {
var file = trashedSearch.next();
files.push([file.getId(),file.getName(),docTypeToText_(file.getMimeType()),file.getUrl()]);
}
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.getRange(1, 1, files.length, files[0].length)
.setValues(files);
return files;
}
Manual file ID collection
(Alternative to automatic retrieval, for reference only.) Since you're just doing this once, though, let's cheat. At the bottom of the Files-list page, use the API Explorer to retrieve the IDs of all your deleted files!
The output is shown just as you'd receive it if you were calling the API from a script.
Cut & paste the output into a text file, and strip it down to just the file ids. (I did that with gvim, it takes just a few commands.) Save the result as a csv file, and pull it into Drive as a spreadsheet. Here's what that will look like. (Do include a header line; the script assumes there is one.)
Process Trashed Files
Now that the list of trashed files is in a spreadsheet, scripting the recovery & move is easy.
/**
* Untrash then move files listed in spreadsheet to rescue folder.
* From: http://stackoverflow.com/a/14541247/1677912
*
* #returns {Number} Count of Rescued files.
*/
function rescueListedFiles() {
var fileList = SpreadsheetApp.getActiveSheet()
.getDataRange().getValues()
.splice(1); // Skip header line
// Find or create target folder
var rescueFldrIterator = DriveApp.getFoldersByName(rescueFldrName);
var rescueFldr = rescueFldrIterator.hasNext() ? rescueFldrIterator.next() : DriveApp.createFolder(rescueFldrName);
var count = 0;
for (var i=0; i<fileList.length; i++) {
var fileId = fileList[i][0];
var file = DriveApp.getFileById(fileId);
// Untrash the file
if (rescueFile( file, rescueFldr )) count++;
}
return( count );
};
try
if (files[i].isTrashed() == true)
I suggest that you put in some diagnostics (Logger.log) to narrow down problems
Remember, files are not in folders. Files have labels that are called folders and there can be more than one folder(label). Even 'trashed' is a label. Setting to trash just creates a trashed label that overrides the other labels(folders). The code below does not move anything. It just resets the labels(folders)
Edit: Trashed is not a label but a condition: everything else holds
for (var i = 0; i < files.length; i++) {
if (files[i].isTrashed()) { // don't forget ()
Logger.log(files[i].getName());
var folders = files[i].getParents();
// remove existing folders(labels)
for(var f = 0; f < folders.length; f++ ) {
files[i].removeFromFolder( folders[f] );
};
// remove trashed label
files[i].setTrashed(false);
// add cestisti label(add to cestisti folder)
files[i].addToFolder(cestisti);
}
}

Check if a file exists in the project in WinRT

I have a WinRT Metro project which displays images based on a selected item. However, some of the images selected will not exist. What I want to be able to do is trap the case where they don't exist and display an alternative.
Here is my code so far:
internal string GetMyImage(string imageDescription)
{
string myImage = string.Format("Assets/MyImages/{0}.jpg", imageDescription.Replace(" ", ""));
// Need to check here if the above asset actually exists
return myImage;
}
Example calls:
GetMyImage("First Picture");
GetMyImage("Second Picture");
So Assets/MyImages/SecondPicture.jpg exists, but Assets/MyImages/FirstPicture.jpg does not.
At first I thought of using the WinRT equivalent of File.Exists(), but there doesn't appear to be one. Without having to go to the extent of trying to open the file and catching an error, can I simply check if either the file exists, or the file exists in the project?
You could use GetFilesAsync from here to enumerate the existing files. This seems to make sense considering you have multiple files which might not exist.
Gets a list of all files in the current folder and its sub-folders. Files are filtered and sorted based on the specified CommonFileQuery.
var folder = await StorageFolder.GetFolderFromPathAsync("Assets/MyImages/");
var files = await folder.GetFilesAsync(CommonFileQuery.OrderByName);
var file = files.FirstOrDefault(x => x.Name == "fileName");
if (file != null)
{
//do stuff
}
Edit:
As #Filip Skakun pointed out, the resource manager has a resource mapping on which you can call ContainsKey which has the benefit of checking for qualified resources as well (i.e. localized, scaled etc).
Edit 2:
Windows 8.1 introduced a new method for getting files and folders:
var result = await ApplicationData.Current.LocalFolder.TryGetItemAsync("fileName") as IStorageFile;
if (result != null)
//file exists
else
//file doesn't exist
There's two ways you can handle it.
1) Catch the FileNotFoundException when trying to get the file:
Windows.Storage.StorageFolder installedLocation =
Windows.ApplicationModel.Package.Current.InstalledLocation;
try
{
// Don't forget to decorate your method or event with async when using await
var file = await installedLocation.GetFileAsync(fileName);
// Exception wasn't raised, therefore the file exists
System.Diagnostics.Debug.WriteLine("We have the file!");
}
catch (System.IO.FileNotFoundException fileNotFoundEx)
{
System.Diagnostics.Debug.WriteLine("File doesn't exist. Use default.");
}
catch (Exception ex)
{
// Handle unknown error
}
2) as mydogisbox recommends, using LINQ. Although the method I tested is slightly different:
Windows.Storage.StorageFolder installedLocation =
Windows.ApplicationModel.Package.Current.InstalledLocation;
var files = await installedLocation.GetFilesAsync(CommonFileQuery.OrderByName);
var file = files.FirstOrDefault(x => x.Name == fileName);
if (file != null)
{
System.Diagnostics.Debug.WriteLine("We have the file!");
}
else
{
System.Diagnostics.Debug.WriteLine("No File. Use default.");
}
BitmapImage has an ImageFailed event that fires if the image can't be loaded. This would let you try to load the original image, and then react if it's not there.
Of course, this requires that you instantiate the BitmapImage yourself, rather than just build the Uri.
Sample checking for resource availability for c++ /cx (tested with Windows Phone 8.1):
std::wstring resPath = L"Img/my.bmp";
std::wstring resKey = L"Files/" + resPath;
bool exists = Windows::ApplicationModel::Resources::Core::ResourceManager::Current->MainResourceMap->HasKey(ref new Platform::String(resKey.c_str()));

How to Read a pre-built Text File in a Windows Phone Application

I've been trying to read a pre-built file with Car Maintenance tips, there's one in each line of my "Tips.txt" file. I've tried to follow around 4 or 5 different approaches but It's not working, it compiles but I get an exception. Here's what I've got:
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamReader sr = new StreamReader(store.OpenFile("Tips.txt", FileMode.Open, FileAccess.Read)))
{
string line;
while ((line = sr.ReadLine()) != null)
{
(App.Current as App).MyTips.Insert(new DoubleNode(line));
}
}
}
I'm getting this "Operation not permitted on IsolatedStorageFileStream", from the info inside the 2nd using statement. I tried with the build action of my "Tips.txt" set to resource, and content, yet I get the same result.
Thanks in advance.
Since you've added it to your project directory, you can't read it using Isolated Storage methods. There are various ways you can load the file. One way would be to set the text file's build type to Resource, then read it in as a stream:
//Replace 'MyProject' with the name of your XAP/Project
Stream txtStream = Application.GetResourceStream(new Uri("/MyProject;component/myTextFile.txt",
UriKind.Relative)).Stream;
using(StreamReader sr = new StreamReader(txtStream))
{
//your code
}