how to copy file from my app Using FileSavePicker UWP - c#

I want copy file in my app to a folder with FileSavePicker. My Code:
var fileSavePicker = new FileSavePicker();
fileSavePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
var filedb = new[] { ".db" };
fileSavePicker.FileTypeChoices.Add("DB", filedb);
fileSavePicker.SuggestedFileName = "BACKUPDB" + System.DateTime.Now.Day + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Year;
//var pathDB = Path.Combine(ApplicationData.Current.LocalFolder.Path, "file.db");
try
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("file.db");
StorageFile localfile = await fileSavePicker.PickSaveFileAsync();
fileSavePicker.SuggestedSaveFile = file;
if (file != null)
{
Debug.WriteLine("file Exists!!");
var fileToSave = await fileSavePicker.PickSaveFileAsync();
....
but my saved file has size 0.
I found how to save text files but my file not is text.

You can use CopyAndReplaceAsync method to copy your local file to the chosen file.
var fileSavePicker = new Windows.Storage.Pickers.FileSavePicker();
fileSavePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
var filedb = new[] { ".db" };
fileSavePicker.FileTypeChoices.Add("DB", filedb);
fileSavePicker.SuggestedFileName = "BACKUPDB" + System.DateTime.Now.Day + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Year;
//var pathDB = Path.Combine(ApplicationData.Current.LocalFolder.Path, "file.db");
try
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("file.db");
StorageFile localfile = await fileSavePicker.PickSaveFileAsync();
if (file != null)
{
Debug.WriteLine("file Exists!!");
await file.CopyAndReplaceAsync(localfile);
}
}
catch(Exception ex)
{
Debug.WriteLine(ex);
}

Related

Read zip for photos with multiple photo file extensions using C#

I've created a method that reads .jpg files and displays them on my screen without extracting.
The var looks like this
var imageName = content.contentid + ".jpg";
content.contentid is too id number of the number + .jpg
But now I want that if there is, for example, a png or jfif file in the zip that it also just shows it.
How do I handle this in this method?
This is my code so far
private void getImage()
{
try
{
var folderName = "protocol-" + _protocol.id + "-" + _protocol.versionnr + ".zip";
var extractPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var zipPath = $"{extractPath}" + "/" + $"{folderName}";
var currentIndex = getCurrentIndex();
var content = _protocol.contents[currentIndex];
List<string> allowedExtensions = new List<string>() { "jpg", "png", "jfif" };
using (var archive = ZipFile.OpenRead(zipPath))
{
foreach (var pictureEntry in archive.Entries)
if (Path.GetFileNameWithoutExtension(pictureEntry.Name).Equals(content.contentid) && allowedExtensions.Contains(Path.GetExtension(pictureEntry.Name)))
{
byte[] buffer;
var length = pictureEntry.Length;
buffer = new byte[length];
pictureEntry.Open().Read(buffer, 0, (int)length);
myImage.Source = ImageSource.FromStream(() => new MemoryStream(buffer));
}
}
}
catch (Exception)
{
}
}
Well you can try this approach:
First define a List of extensions that you want to check against:
List<string> allowedExtensions = new List<string>() {"jpg", "png", "jfif" };
then change your if (pictureEntry.Name == imageName) for
if (Path.GetFileNameWithoutExtension(pictureEntry.Name) == content.contentid &&
allowedExtensions.Contains(Path.GetExtension(pictureEntry.Name)))
Also this line var imageName = content.contentid + ".jpg"; is innecesary as imageName didn't be used:

Downloading a directory using SSH.NET SFTP in C#

I am using Renci.SSH and C# to connect to my Unix server from a Windows machine. My code works as expected when the directory contents are only files, but if the directory contains a folder, I get this
Renci.SshNet.Common.SshException: 'Failure'
This is my code, how can I update this to also download a directory (if exists)
private static void DownloadFile(string arc, string username, string password)
{
string fullpath;
string fp;
var options = new ProgressBarOptions
{
ProgressCharacter = '.',
ProgressBarOnBottom = true
};
using (var sftp = new SftpClient(Host, username, password))
{
sftp.Connect();
fp = RemoteDir + "/" + arc;
if (sftp.Exists(fp))
fullpath = fp;
else
fullpath = SecondaryRemoteDir + d + "/" + arc;
if (sftp.Exists(fullpath))
{
var files = sftp.ListDirectory(fullpath);
foreach (var file in files)
{
if (file.Name.ToLower().Substring(0, 1) != ".")
{
Console.WriteLine("Downloading file from the server...");
Console.WriteLine();
using (var pbar = new ProgressBar(100, "Downloading " + file.Name + "....", options))
{
SftpFileAttributes att = sftp.GetAttributes(fullpath + "/" + file.Name);
var fileSize = att.Size;
var ms = new MemoryStream();
IAsyncResult asyncr = sftp.BeginDownloadFile(fullpath + "/" + file.Name, ms);
SftpDownloadAsyncResult sftpAsyncr = (SftpDownloadAsyncResult)asyncr;
int lastpct = 0;
while (!sftpAsyncr.IsCompleted)
{
int pct = (int)((long)sftpAsyncr.DownloadedBytes / fileSize) * 100;
if (pct > lastpct)
for (int i = 1; i < pct - lastpct; i++)
pbar.Tick();
}
sftp.EndDownloadFile(asyncr);
Console.WriteLine("Writing File to disk...");
Console.WriteLine();
string localFilePath = "C:\" + file.Name;
var fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write);
ms.WriteTo(fs);
fs.Close();
ms.Close();
}
}
}
}
else
{
Console.WriteLine("The arc " + arc + " does not exist");
Console.WriteLine();
Console.WriteLine("Please press any key to close this window");
Console.ReadKey();
}
}
}
BeginDownloadFile downloads a file. You cannot use it to download a folder. For that you need to download contained files one by one.
The following example uses synchronous download (DownloadFile instead of BeginDownloadFile) for simplicity. After all, you are synchronously waiting for asynchronous download to complete anyway. To implement a progress bar with synchronous download, see Displaying progress of file download in a ProgressBar with SSH.NET.
public static void DownloadDirectory(
SftpClient sftpClient, string sourceRemotePath, string destLocalPath)
{
Directory.CreateDirectory(destLocalPath);
IEnumerable<SftpFile> files = sftpClient.ListDirectory(sourceRemotePath);
foreach (SftpFile file in files)
{
if ((file.Name != ".") && (file.Name != ".."))
{
string sourceFilePath = sourceRemotePath + "/" + file.Name;
string destFilePath = Path.Combine(destLocalPath, file.Name);
if (file.IsDirectory)
{
DownloadDirectory(sftpClient, sourceFilePath, destFilePath);
}
else
{
using (Stream fileStream = File.Create(destFilePath))
{
sftpClient.DownloadFile(sourceFilePath, fileStream);
}
}
}
}
}

If the file size is 0kb, it is not displayed on the gridview and the file is deleted

I have a gridview that displays some files. I would like if the file size is 0 kb, then the file is not displayed and deleted, while other files are still displayed
Code:
StorageFolder cover = await komik.GetFolderAsync("cover");
foreach (StorageFile file in sortedfiles)
{
bool bukuada = true;
Buku buku = new Buku();
buku.Judul = file.DisplayName.ToString();
BasicProperties pro = await file.GetBasicPropertiesAsync();
if (pro.Size != 0)
{
StorageFile thumbFile = file;
try
{
thumbFile = await cover.GetFileAsync(file.DisplayName.ToString() + ".jpg");
BitmapImage bi = new BitmapImage();
bi.SetSource(await thumbFile.OpenAsync(FileAccessMode.Read));
buku.Cover = bi;
datasource.Add(buku);
loading.IsActive = false;
this.itemGridView.ItemsSource = datasource;
}
catch
{
}
}
}
If I use the code above, then if there is a file whose size is 0 kb, then all files are not displayed. How do I get only 0 kb files that are not displayed and deleted, while others are still showing?
Your code is setting the ItemsSource in the loop repeatedly, which is less efficient, but otherwise should not affect the result - even if there are some files of 0 size, they should be skipped and the "actual" files should cause the datasource to be updated.
My concern is regarding the following:
thumbFile = await cover.GetFileAsync(file.DisplayName.ToString() + ".jpg");
The DisplayName property has been known to sometimes return the file name including
the extension. I would suggest rather using the following:
thumbFile = await cover.GetFileAsync( Path.GetFileNameWithoutExtension( file.Name ) + ".jpg" );
Name property returns the full name of the file, so if we apply Path.GetFileNameWithoutExtension, the extension will definitely be removed, so the result will be what you want.
If that doesn't help, change the catch expression to catch ( Exception ex ) and then put a breakpoint inside the catch block, because if the datasource variable is not filled out with data, there must be an exception happening beforehand.
For you had set the this.itemGridView.ItemsSource = datasource; when the pro.Size != 0
Try to use this code.
StorageFolder cover = await komik.GetFolderAsync("cover");
List<StorageFile> deletedFileList = new List<StorageFile>();
foreach (StorageFile file in sortedfiles)
{
bool bukuada = true;
Buku buku = new Buku();
buku.Judul = file.DisplayName.ToString();
BasicProperties pro = await file.GetBasicPropertiesAsync();
if (pro.Size != 0)
{
StorageFile thumbFile = file;
try
{
thumbFile = await cover.GetFileAsync(file.DisplayName.ToString() + ".jpg");
BitmapImage bi = new BitmapImage();
bi.SetSource(await thumbFile.OpenAsync(FileAccessMode.Read));
buku.Cover = bi;
datasource.Add(buku);
loading.IsActive = false;
}
catch
{
}
}
else
{
deletedFileList.Add(file);
}
}
// display the data source.
this.itemGridView.ItemsSource = datasource;
// delete the file
foreach(var temp in deletedFileList)
{
try
{
await temp.DeleteAsync();
}
catch(IOException)
{
}
}

Windows Universal - Display images from Assets

I'm trying to scroll through images in my app, but I'm having trouble figuring out how to populate my list. The images are named using numbers from 1.jpg upwards. If anyone could help it would be great.
async private void Exec()
{
// Get the file location.
StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
string myImageFolder = (appFolder.Path + "\\Assets\\Images");
int imageNumber = 1;
List<Uri> fileList = new List<Uri>();
foreach (var fileItem in fileList)
{
string imageFileName = imageNumber + ".jpg";
Uri uri = new Uri(myImageFolder + "/" + imageFileName);
fileList.Add(uri);
image.Source = new BitmapImage(new Uri(uri.ToString()));
await Task.Delay(TimeSpan.FromSeconds(1));
imageNumber++;
}
}
UPDATE
I have tried to create a workaround and do this without the foreach statement but its crashing when testing if the next file exists: :(
async private void Exec()
{
// Get the file location.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path = root + #"\Assets\Images";
StorageFolder appFolder = await StorageFolder.GetFolderFromPathAsync(path);
int imageNumber = 1;
int test = imageNumber;
do
{
string imageFileName = imageNumber + ".jpg";
Uri uri = new Uri(path + "\\" + imageFileName);
image.Source = new BitmapImage(new Uri(uri.ToString()));
await Task.Delay(TimeSpan.FromSeconds(1));
test = imageNumber + 1;
imageNumber++;
string testFile = test + ".jpg";
Uri uri1 = new Uri(path + "\\" + testFile);
if (await appFolder.TryGetItemAsync(uri1.ToString()) != null)
{
test = 99999;
}
}
while (test != 99999);
}
Your list does not contain any items. Your foreach will never run, as there will be no entries in your list.
You need to go through all paths in myImageFolder-root and add those uris to the list, then you can just use them in a foreach to create images and set their source, for every uri in the list.
Also imageNumber is un-needed then as you will have the URIs.
Prep the list of URIs first, by traversing the folder. Then modify the existing foreach to use those to build image objects.
Also, refrain from adding to a collection WHILE iterating it...
I have this working, and not a single foreach was required :D Thanks #Richard Eriksson
async private void Exec()
{
// Get the file location.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path = root + #"\Assets\Images";
StorageFolder appFolder = await StorageFolder.GetFolderFromPathAsync(path);
int imageNumber = 1;
int test = imageNumber;
do
{
string imageFileName = imageNumber + ".jpg";
Uri uri = new Uri(path + "\\" + imageFileName);
image.Source = new BitmapImage(new Uri(uri.ToString()));
await Task.Delay(TimeSpan.FromSeconds(1));
test = imageNumber + 1;
imageNumber++;
string testFile = test + ".jpg";
if (await appFolder.TryGetItemAsync(testFile) != null)
{
test = 99999;
}
else
{
test = 1;
}
}
while (test == 99999);
}

How to know when a method finish in controller

I have a problem with this method, i want to return a PDF file and when the method it's over i want to delete de file from the directory.
public ActionResult DescargaPdfCompara(string id)
{
var rutaPdf = string.Empty;
var type = "application/pdf";
try
{
DateTime ahora = DateTime.Now;
var numeroAleatorio = new Random();
int numeroRandomico = numeroAleatorio.Next(100000000, 1000000000);
string Ruta = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Reportes\" + Convert.ToString(ahora.Year + ahora.Month + ahora.Day + ahora.Hour + ahora.Minute + ahora.Second + numeroRandomico) + ".pdf");
var result = SimuModel.ObtenerSabanaReporteComparativo(id);
var resumen = SimuModel.ObtenerPreExcel(result);
SimuModel.GenerarPdfCompa(result, resumen, Ruta);
rutaPdf = Ruta;
return File(rutaPdf, type);
}
catch (Exception e)
{
throw e;
}
finally
{
System.IO.File.Delete(rutaPdf);
}
}
In the finally i delete the file but i got an error because the method can't find the file, for some reason the method delete the file before return it.
PD: Sorry for my english, i'm from Chile.
Thanks fro your answers!
You can use System.IO.File.ReadAllBytes to read all the file contents to memory, then delete the file and return the contents with another overload of Controller.File method:
public ActionResult GetFile()
{
var fileName = Path.GetTempFileName();
System.IO.File.WriteAllText(fileName, "Hola, Chile!");
var bytes = System.IO.File.ReadAllBytes(fileName);
System.IO.File.Delete(fileName);
return File(bytes, "text/plain", "file.txt");
}
Change return type ContentResult
remove finally section.
public ContentResult DescargaPdfCompara(string id)
{
var rutaPdf = string.Empty;
var type = "application/pdf";
try
{
DateTime ahora = DateTime.Now;
var numeroAleatorio = new Random();
int numeroRandomico = numeroAleatorio.Next(100000000, 1000000000);
string Ruta = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Reportes\" + Convert.ToString(ahora.Year + ahora.Month + ahora.Day + ahora.Hour + ahora.Minute + ahora.Second + numeroRandomico) + ".pdf");
var result = SimuModel.ObtenerSabanaReporteComparativo(id);
var resumen = SimuModel.ObtenerPreExcel(result);
SimuModel.GenerarPdfCompa(result, resumen, Ruta);
rutaPdf = Ruta;
return Content(rutaPdf, type);
}
catch (Exception e)
{
throw e;
}
}

Categories

Resources