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);
}
Related
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:
I have the following code which works fine for Move, but doesn't work for copy
// relativeSourceFolderUrl = "/SubSeries/DEV010/files/dev010-007-2018/parent/copyThisFolder"
// relativeDestinationFolderUrl= "/SubSeries/DEV010/files/dev010-007-2018/parent/child"
// fileName = "copyThisFoler"
// moveItem = false
public Folder MoveOrCopyFolder(String relativeSourceFolderUrl, String relativeDestinationFolderUrl, String fileName, bool moveItem)
{
Folder folder = ClientContext.Web.GetFolderByServerRelativeUrl(relativeDestinationFolderUrl);
// Check if file or folder exists and alter name
fileName = CheckFileOrFolderExistsInFolder(fileName, folder, false);
// In this case the function returns a fileName of "copyThisFolder"
var file = ClientContext.Web.GetFileByServerRelativeUrl(relativeSourceFolderUrl);
ClientContext.Load(file.ListItemAllFields);
ClientContext.ExecuteQuery();
if (moveItem)
file.MoveTo(relativeDestinationFolderUrl + "/" + fileName, MoveOperations.None);
else
file.CopyTo(relativeDestinationFolderUrl + "/" + fileName, false);
ClientContext.ExecuteQuery();
return null;
}
It breaks on this line
file.CopyTo(relativeDestinationFolderUrl + "/" + fileName, false);
The error is
Additional information: The URL '/SubSeries/DEV010/files/dev010-007-2018/parent/copythisfolder' is invalid. It may refer to a nonexistent file or folder, or refer to a valid file or folder that is not in the current Web.
The Move works, but its odd that similar code doesn't work for copy.
In the end I used this post:
https://sharepoint.stackexchange.com/questions/97471/copy-all-items-in-a-folder-to-another-location/250233?noredirect=1#comment266907_250233
Which lead me to this solution:
public void CopyFiles(string listTitle, string srcRelativeSource, string destRelativeSource)
{
var srcList = ClientContext.Web.Lists.GetByTitle(listTitle);
var qry = CamlQuery.CreateAllItemsQuery();
qry.FolderServerRelativeUrl = string.Format("/{0}", srcRelativeSource);
var srcItems = srcList.GetItems(qry);
ClientContext.Load(srcItems, icol => icol.Include(i => i.FileSystemObjectType, i => i["FileRef"], i => i.File));
ClientContext.ExecuteQuery();
createThisFolder(destRelativeSource);
foreach (var item in srcItems)
{
switch (item.FileSystemObjectType)
{
case FileSystemObjectType.Folder:
var destFolderUrl = ((string)item["FileRef"]).ToLower().Replace(srcRelativeSource, destRelativeSource);
createThisFolder(destFolderUrl);
break;
case FileSystemObjectType.File:
var destFileUrl = item.File.ServerRelativeUrl.ToLower().Replace(srcRelativeSource, destRelativeSource);
item.File.CopyTo(destFileUrl, true);
ClientContext.ExecuteQuery();
break;
}
}
}
private void createThisFolder(string destFolderUrl)
{
//change destFolderUrl into absolute url
Uri u = new Uri(ClientContext.Web.Context.Url);
//remove the string after the last slash
int idx = destFolderUrl.LastIndexOf('/');
string path = destFolderUrl.Substring(0, idx);
string lastFolder = destFolderUrl.Split('/').Last();
string filtered = (path.StartsWith("/")) ? path.Substring(1) : path;
string url = u.GetLeftPart(UriPartial.Authority) + "/" + filtered;
CreateFolder(url, lastFolder);
}
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);
}
}
}
}
}
I have an issue with Files.
I am doing an image importer so clients put their files on an FTP server and then they can import it in the application.
During the import process I copy the file in the FTP Folder to another folder with File.copy
public List<Visuel> ImportVisuel(int galerieId, string[] images)
{
Galerie targetGalerie = MemoryCache.GetGaleriById(galerieId);
List<FormatImage> listeFormats = MemoryCache.FormatImageToList();
int i = 0;
List<Visuel> visuelAddList = new List<Visuel>();
List<Visuel> visuelUpdateList = new List<Visuel>();
List<Visuel> returnList = new List<Visuel>();
foreach (string item in images)
{
i++;
Progress.ImportProgress[Progress.Guid] = "Image " + i + " sur " + images.Count() + " importées";
string extension = Path.GetExtension(item);
string fileName = Path.GetFileName(item);
string originalPath = HttpContext.Current.Request.PhysicalApplicationPath + "Uploads\\";
string destinationPath = HttpContext.Current.Server.MapPath("~/Images/Catalogue") + "\\";
Visuel importImage = MemoryCache.GetVisuelByFilName(fileName);
bool update = true;
if (importImage == null) { importImage = new Visuel(); update = false; }
Size imageSize = importImage.GetJpegImageSize(originalPath + fileName);
FormatImage format = listeFormats.Where(f => f.width == imageSize.Width && f.height == imageSize.Height).FirstOrDefault();
string saveFileName = Guid.NewGuid() + extension;
File.Copy(originalPath + fileName, destinationPath + saveFileName);
if (format != null)
{
importImage.format = format;
switch (format.key)
{
case "Catalogue":
importImage.fileName = saveFileName;
importImage.originalFileName = fileName;
importImage.dossier = targetGalerie;
importImage.dossier_id = targetGalerie.id;
importImage.filePath = "Images/Catalogue/";
importImage.largeur = imageSize.Width;
importImage.hauteur = imageSize.Height;
importImage.isRoot = true;
if (update == false) { MemoryCache.Add(ref importImage); returnList.Add(importImage); }
if (update == true) visuelUpdateList.Add(importImage);
foreach (FormatImage f in listeFormats)
{
if (f.key.StartsWith("Catalogue_"))
{
string[] keys = f.key.Split('_');
string destinationFileName = saveFileName.Insert(saveFileName.IndexOf('.'), "-" + keys[1].ToString());
string destinationFileNameDeclinaison = destinationPath + destinationFileName;
VisuelResizer declinaison = new VisuelResizer();
declinaison.Save(originalPath + fileName, f.width, f.height, 1000, destinationFileNameDeclinaison);
Visuel visuel = MemoryCache.GetVisuelByFilName(fileName.Insert(fileName.IndexOf('.'), "-" + keys[1].ToString()));
update = true;
if (visuel == null) { visuel = new Visuel(); update = false; }
visuel.parent = importImage;
visuel.filePath = "Images/Catalogue/";
visuel.fileName = destinationFileName;
visuel.originalFileName = string.Empty;
visuel.format = f;
//visuel.dossier = targetGalerie; On s'en fout pour les déclinaisons
visuel.largeur = f.width;
visuel.hauteur = f.height;
if (update == false)
{
visuelAddList.Add(visuel);
}
else
{
visuelUpdateList.Add(visuel);
}
//importImage.declinaisons.Add(visuel);
}
}
break;
}
}
}
MemoryCache.Add(ref visuelAddList);
// FONCTION à implémenter
MemoryCache.Update(ref visuelUpdateList);
return returnList;
}
After some processes on the copy (the original file is no more used)
the client have a pop-up asking him if he wants to delete the original files in the ftp folder.
If he clicks on Ok another method is called on the same controller
and this method use
public void DeleteImageFile(string[] files)
{
for (int i = 0; i < files.Length; i++)
{
File.Delete(HttpContext.Current.Request.PhysicalApplicationPath + files[i].Replace(#"/", #"\"));
}
}
This method works fine and really delete the good files when I use it in other context.
But here I have an error message:
Process can't acces to file ... because it's used by another process.
Someone have an idea?
Thank you.
Here's the screenshot of Process Explorer
There are couple of thing you can do here.
1) If you can repro it, you can use Process Explorer at that moment and see which process is locking the file and if the process is ur process then making sure that you close the file handle after your work is done.
2) Use try/catch around the delete statement and retry after few seconds to see if the file handle was released.
3) If you can do it offline you can put in some queue and do the deletion on it later on.
You solve this by using c# locks. Just embed your code inside a lock statement and your threads will be safe and wait each other to complete processing.
I found the solution:
in my import method, there a call to that method
public void Save(string originalFile, int maxWidth, int maxHeight, int quality, string filePath)
{
Bitmap image = new Bitmap(originalFile);
Save(ref image, maxWidth, maxHeight, quality, filePath);
}
The bitmap maintains the file opened blocking delete.
just added
image.Dispose();
in the methos and it work fine.
Thank you for your help, and thank you for process explorer. Very useful tool
When we are copying images in one folder to another folder, images are going to copy one by one, then it takes more time when thousands's of images are copying, Is there any Possibility to copy Multiple images at a time? "This is My code"
int avilableCharts = 0;
int unavialableCharts = 0;
string chartid;
int count = 0;
StreamReader rd = new StreamReader(txtFileName.Text);
StreamWriter tw = new StreamWriter("C:\\LogFiles\\SucessfullyMovedImages.txt");
StreamWriter tw1 = new StreamWriter("C:\\LogFiles\\UnavailableImages.txt");
DirectoryInfo dirinfo = new DirectoryInfo(txtSourceFolder.Text);
FileInfo[] file = dirinfo.GetFiles("*.pdf");
while (!rd.EndOfStream)
{
chartid = rd.ReadLine() + ".pdf";
count = count + 1;
worker.ReportProgress(count);
string FName = string.Empty;
if (File.Exists(txtSourceFolder.Text + chartid))
{
File.Copy(txtSourceFolder.Text + chartid , txtDestinationFolder.Text + chartid );
avilableCharts = avilableCharts + 1;
tw.WriteLine(chartid);
}
else
{
unavialableCharts = unavialableCharts + 1;
tw1.WriteLine(chartid);
}
}
tw.Close();
tw1.Close();
MessageBox.Show("Successfully Copied Images are :" + avilableCharts);
MessageBox.Show("Total Unavilable Images are : " + unavialableCharts);
use below code :
public class SimpleFileMove
{
static void Main()
{
string sourceFile = #"C:\Users\Public\public\test.txt";
string destinationFile = #"C:\Users\Public\private\test.txt";
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);
// To move an entire directory. To programmatically modify or combine
// path strings, use the System.IO.Path class.
System.IO.Directory.Move(#"C:\Users\Public\public\test\", #"C:\Users\Public\private");
}
}