I want to know how to get files from the directory under Picture Library.(C:\Users\username\Pictures\MyFoler)
I know how to get files and folders from PicturesLibrary.
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
IReadOnlyList<StorageFile> fileLists = await picturesFolder.GetFilesAsync();
IReadOnlyList<StorageFolder> folderLists = await picturesFolder.GetFoldersAsync();
Using the same general mechanism, StorageFolder exposes GetFoldersAsync and GetFilesAsync.
This code, added after what you have, would get a list of files in Pictures\MyFolder
StorageFolder myFolder = folderLists.Where(f => f.DisplayName == "MyFolder").FirstOrDefault();
if (myFolder != null)
{
ReadOnlyList<StorageFile> myPictures = await myFolder.GetFilesAsync();
}
Related
I have +600 product images on my mac already cut out and catalogued in their own folder. They are all PSD's and I need a script that will do the following.
Grab the name of the folder
Grab all the PSD's in said folder
Combine them in one big PSD in the right order (the filenames are saved sequentially as 1843, 1845, 1846 so they need to open in that order)
save that PSD
save the separate layers as PNG with the name from the folder + _1, _2, _3
I have previous experience in Bash (former Linux user) and tried for hours in Automator but to no success.
Welcome to Stack Overflow. The quick answer is yes this is possible to do via scripting. I might even suggest breaking down into two scripts, one to grab and save the PSDs and the second to save out the layers.
It's not very clear about "combining" the PSDs or about "separate layers, only I don't know if they are different canvas sizes, where you want each PSD to be positioned (x, y offsets & layering) Remember none of use have your files infront of us to refer from.
In short, if you write out pseudo code of what is it you expect your code to do it makes it easier to answer your question.
Here's a few code snippets to get you started:
This will open a folder and retrieve alls the PSDs as an array:
// get all the files to process
var folderIn = Folder.selectDialog("Please select folder to process");
if (folderIn != null)
{
var tempFileList = folderIn.getFiles();
}
var fileList = new Array(); // real list to hold images, not folders
for (var i = 0; i < tempFileList.length; i++)
{
// get the psd extension
var ext = tempFileList[i].toString();
ext = ext.substring(ext.lastIndexOf("."), ext.length);
if (tempFileList[i] instanceof File)
{
if (ext == ".psd") fileList.push (tempFileList[i]);
// else (alert("Ignoring " + tempFileList[i]))
}
}
alert("Files:\n" + fileList.length);
You can save a png with this
function save_png(afilePath)
{
// Save as a png
var pngFile = new File(afilePath);
pngSaveOptions = new PNGSaveOptions();
pngSaveOptions.embedColorProfile = true;
pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
pngSaveOptions.matte = MatteType.NONE; pngSaveOptions.quality = 1;
activeDocument.saveAs(pngFile, pngSaveOptions, false, Extension.LOWERCASE);
}
To open a psd just use
app.open(fileRef);
To save it
function savePSD(afilePath)
{
// save out psd
var psdFile = new File(afilePath);
psdSaveOptions = new PhotoshopSaveOptions();
psdSaveOptions.embedColorProfile = true;
psdSaveOptions.alphaChannels = true;
activeDocument.saveAs(psdFile, psdSaveOptions, false, Extension.LOWERCASE);
}
We are using the MultipartFormDataStreamProviderto save file upload by clients. I have a hard requirement that file size must be greater than 1KB. The easiest thing to do would of course be the save the file to disk and then look at the file unfortunately i can't do it like this. After i save the file to disk i don't have the ability to access it so i need to look at the file before its saved to disk. I've been looking at the properties of the stream provider to try to figure out what the size of the file is but unfortunately i've been unsuccessful.
The test file i'm using is 1025 bytes.
MultipartFormDataStreamProvider.BufferSize is 4096
Headers.ContentDisposition.Size is null
ContentLength is null
Is there a way to determine file size before it's saved to the file system?
Thanks to Guanxi i was able to formulate a solution. I used his code in the link as the basis i just added a little more async/await goodness :). I wanted to add the solution just in case it helps anyone else:
private async Task SaveMultipartStreamToDisk(Guid guid, string fullPath)
{
var user = HttpContext.Current.User.Identity.Name;
var multipartMemoryStreamProvider = await Request.Content.ReadAsMultipartAsync();
foreach (var content in multipartMemoryStreamProvider.Contents)
{
using (content)
{
if (content.Headers.ContentDisposition.FileName != null)
{
var existingFileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
Log.Information("Original File name was {OriginalFileName}: {guid} {user}", existingFileName, guid,user);
using (var st = await content.ReadAsStreamAsync())
{
var ext = Path.GetExtension(existingFileName.Replace("\"", string.Empty));
List<string> validExtensions = new List<string>() { ".pdf", ".jpg", ".jpeg", ".png" };
//1024 = 1KB
if (st.Length > 1024 && validExtensions.Contains(ext, StringComparer.OrdinalIgnoreCase))
{
var newFileName = guid + ext;
using (var fs = new FileStream(Path.Combine(fullPath, newFileName), FileMode.Create))
{
await st.CopyToAsync(fs);
Log.Information("Completed writing {file}: {guid} {user}", Path.Combine(fullPath, newFileName), guid, HttpContext.Current.User.Identity.Name);
}
}
else
{
if (st.Length < 1025)
{
Log.Warning("File of length {FileLength} bytes was attempted to be uploaded: {guid} {user}",st.Length,guid,user);
}
else
{
Log.Warning("A file of type {FileType} was attempted to be uploaded: {guid} {user}", ext, guid,user);
}
var responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content =
st.Length < 1025
? new StringContent(
$"file of length {st.Length} does not meet our minumim file size requirements")
: new StringContent($"a file extension of {ext} is not an acceptable type")
};
throw new HttpResponseException(responseMessage);
}
}
}
}
}
You can also read the request contents without using MultipartFormDataStreamProvider. In that case all of the request contents (including files) would be in memory. I have given an example of how to do that at this link.
In this case you can read header for file size or read stream and check the file size. If it satisfy your criteria then only write it to desire location.
I'm using the following code on Mac using Mono to unzip a zip file. The zip file contains entries under directories (for example foo/bar.txt). However, in the unzipped directory, instead of creating a directory foo with a file bar.txt, FastZip creates a file foo\bar.txt. How do I get around this?
FastZip fz = new FastZip();
string filePath = #"path\to\myfile.zip";
fz.ExtractZip(filePath, #"path\to\unzip\to", null);
This creates a file foo\bar.txt in path\to\unzip\to.
Apparently cannot use FastZip for this case so I ended up writing my own unzipping mechanism:
string filePath = #"path\to\myfile.zip";
string unzipDir = #"path\to\unzip\to";
using (var zipFile = new ZipFile(filePath))
{
foreach (var zipEntry in zipFile.OfType<ZipEntry>())
{
var unzipPath = Path.Combine(unzipDir, zipEntry.Name);
var directoryPath = Path.GetDirectoryName(unzipPath);
// create directory if needed
if (directoryPath.Length > 0)
{
Directory.CreateDirectory(directoryPath);
}
// unzip the file
var zipStream = zipFile.GetInputStream(zipEntry);
var buffer = new byte[4096];
using (var unzippedFileStream = File.Create(unzipPath))
{
StreamUtils.Copy(zipStream, unzippedFileStream, buffer);
}
}
}
use a forward slash to separate folders when creating the zip
Problem accessing mp3 files in WinRT app.
'System.UnauthorizedAccessException' occurs when app tries to open a mp3 file by name in the same folder as a file returned by FileOpenPicker. Put another way, the user picks an info file in Documents with the same name as a mp3 file. App opens the info file just fine but cannot open the mp3 file.
For example: I have a pair of files (file1.info) and (file1.mp3). A filepicker allows selecting a (*.info) file.
The user selects (file1.info). The app then opens both (file1.info) and (file1.mp3). Both files reside in a DocumentsLibrary folder, but are NOT in the MusicLibrary. The problem is when I try to open (file1.mp3) I get the 'UnauthorizedAccessException'.
To prepro the issue:
Files:
Copy an mp3 file to Documents.
Create a text file with the same base name as the mp3 file and change its extension to .info.
In Package.appxmanifest > Declarations add a 'File Type Associations' declaration. Check 'Open is safe'. Add
supported file types '.mp3' and '.info'. Leave 'Content type' empty.
Code:
Dim file as StorageFile
Dim fileopenpicker As FileOpenPicker
Dim infofile As StorageFile
Dim mp3file As StorageFile
Dim filename As String
fileopenpicker = New FileOpenPicker()
fileopenpicker.FileTypeFilter.Add(".info")
fileopenpicker.FileTypeFilter.Add(".mp3")
fileopenpicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary
file = Await fileopenpicker.PickSingleFileAsync()
If file.Path.EndsWith(".info") Then
infofile = file
filename = file.Path.Substring(0, file.Path.Length - 4) & "mp3"
' This command fails with 'System.UnauthorizedAccessException'
mp3file = Await StorageFile.GetFileFromPathAsync(filename)
Else 'file is an mp3 file
mp3file = file
filename = file.Path.Substring(0, file.Path.Length - 3) & "info"
' This command succeeds!
infofile = Await StorageFile.GetFileFromPathAsync(filename)
End If
So it appears that there is some specific problem with opening an mp3 file when the file is not actually chosen by the fileopenpicker.
I checked this issue with an app that has the capability Documents Library and the filetypes .mp3 and .info declared. I figured out that it seems to be a very strange bug. If you pass the path to the documents library folder using an uppercase drive letter after having opened a FileOpenPicker you get an UnauthorizedAccessException. Using the path with a lowercase drive letter works. Strangely you can use an uppercase drive letter before having opened a FileOpenPicker.
So the workaround is to lowercase the path.
Here's the code I used (C#):
// Trying to get some files from the documents library
// Note: F:\Program Data is my primary documents library folder
string mp3FilePath = #"F:\Program Data\2Mann1Maus.mp3";
// This works even if the drive letter is uppercase
StorageFile file1 = await StorageFile.GetFileFromPathAsync(mp3FilePath);
// It also works with a lowercase drive letter
string infoFilePath = #"f:\Program Data\2Mann1Maus.info";
StorageFile file2 = await StorageFile.GetFileFromPathAsync(infoFilePath);
FileOpenPicker fileopenpicker = new FileOpenPicker();
fileopenpicker.FileTypeFilter.Add(".info");
fileopenpicker.FileTypeFilter.Add(".mp3");
fileopenpicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
StorageFile file = await fileopenpicker.PickSingleFileAsync();
if (file.Path.EndsWith(".info"))
{
string filename = file.Path.Substring(0, file.Path.Length - 4) + "mp3";
// This works
string testFileName1 = filename.Substring(0, 1).ToLower() +
filename.Substring(1, filename.Length - 1);
StorageFile mp3file1 = await StorageFile.GetFileFromPathAsync(testFileName1);
// This works as well
string testFileName2 = filename.ToLower();
StorageFile mp3file2 = await StorageFile.GetFileFromPathAsync(testFileName2);
// This does cause an UnauthorizedAccessException
StorageFile mp3file3 = await StorageFile.GetFileFromPathAsync(filename);
}
else
{
StorageFile mp3file = file;
String filename = file.Path.Substring(0, file.Path.Length - 3) + "info";
// This works
string testFileName1 = filename.Substring(0, 1).ToLower() +
filename.Substring(1, filename.Length - 1);
StorageFile infoFile1 = await StorageFile.GetFileFromPathAsync(testFileName1);
// This works as well
string testFileName2 = filename.ToLower();
StorageFile infoFile2 = await StorageFile.GetFileFromPathAsync(testFileName2);
// This does cause an UnauthorizedAccessException
StorageFile infoFile3 = await StorageFile.GetFileFromPathAsync(filename);
}
I am trying to upload a file via a form and then save in in SQL as a blob.
I already have my form working fine, my database is fully able to take the blob and I have a controller that take the file, saves it in a local directory:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(int id, HttpPostedFileBase uploadFile)
{
//allowed types
string typesNonFormatted = "text/plain,application/msword,application/pdf,image/jpeg,image/png,image/gif";
string[] types = typesNonFormatted.Split(',');
//
//Starting security check
//checking file size
if (uploadFile.ContentLength == 0 && uploadFile.ContentLength > 10000000)
ViewData["StatusMsg"] = "Could not upload: File too big (max size 10mb) or error while transfering the file.";
//checking file type
else if(types.Contains(uploadFile.ContentType) == false)
ViewData["StatusMsg"] = "Could not upload: Illigal file type!<br/> Allowed types: images, Ms Word documents, PDF, plain text files.";
//Passed all security checks
else
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName)); //generating path
uploadFile.SaveAs(filePath); //saving file to final destination
ViewData["StatusMsg"] = "Uploaded: " + uploadFile.FileName + " (" + Convert.ToDecimal(uploadFile.ContentLength) / 1000 + " kb)";
//saving file to database
//
//MISSING
}
return View("FileUpload", null);
}
Now all I am missing is putting the file in the database. I could not find anything on the subject... I found some way to do it in a regular website but nothing in MVC2.
Any kind of help would be welcome!
Thank you.
This could help: http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/
Since you have HttpPostedFileBase in your controllers method, all you need to do is:
int length = uploadFile.ContentLength;
byte[] tempImage = new byte[length];
myDBObject.ContentType = uploadFile.ContentType;
uploadFile.InputStream.Read(tempImage, 0, length);
myDBObject.ActualImage = tempImage ;
HttpPostedFileBase has a InputStream property
Hope this helps.
Alright thanks to kheit, I finaly got it working. Here's the final solution, it might help someone out there.
This script method takes all the file from a directory and upload them to the database:
//upload all file from a directory to the database as blob
public void UploadFilesToDB(long UniqueId)
{
//directory path
string fileUnformatedPath = "../Uploads/" + UniqueId; //setting final path with unique id
//getting all files in directory ( if any)
string[] FileList = System.IO.Directory.GetFiles(HttpContext.Server.MapPath(fileUnformatedPath));
//for each file in direcotry
foreach (var file in FileList)
{
//extracting file from directory
System.IO.FileStream CurFile = System.IO.File.Open(file, System.IO.FileMode.Open);
long fileLenght = CurFile.Length;
//converting file to a byte array (byte[])
byte[] tempFile = new byte[fileLenght];
CurFile.Read(tempFile, 0, Convert.ToInt32(fileLenght));
//creating new attachment
IW_Attachment CurAttachment = new IW_Attachment();
CurAttachment.attachment_blob = tempFile; //setting actual file
string[] filedirlist = CurFile.Name.Split('\\');//setting file name
CurAttachment.attachment_name = filedirlist.ElementAt(filedirlist.Count() - 1);//setting file name
//uploadind attachment to database
SubmissionRepository.CreateAttachment(CurAttachment);
//deleting current file fromd directory
CurFile.Flush();
System.IO.File.Delete(file);
CurFile.Close();
}
//deleting directory , it should be empty by now
System.IO.Directory.Delete(HttpContext.Server.MapPath(fileUnformatedPath));
}
(By the way IW_Attachment is the name of one of my database table)