FilePicker return name and path as strings - c#

I've got a file Save and file open picker that im now trying to integrate the ability to save the Path and FileName as public variable that will be used across the whole project through different methods etc.
I've currently got a SaveFileClass and OpenFileClass.
I've seen examples of using the OpenFileDialog to return the save directory although I don't believe these are suitable for what im after. Maybe in some shape or form but dont seem to make much sense for the FileOpenPicker and FileSavePicker I have in use currently.
What I have currently (minus the returning directories) is this:
public async Task<IStorageFile> OpenFileAsync()
{
FileOpenPicker openPicker = new FileOpenPicker
{
ViewMode = PickerViewMode.List,
SuggestedStartLocation = PickerLocationId.DocumentsLibrary
};
openPicker.FileTypeFilter.Add(".txt");
openPicker.FileTypeFilter.Add(".csv");
return await openPicker.PickSingleFileAsync();
}
This passes back to the MainPage.
Within here, i would like to have a variable to store the selected file path and the selected file name as a string. These will then be used around the project when it comes to quick saving/auto saving and when building my class to load files.
Im just after whether or not FilePicker has this functionality because my understanding of the documentation is a little limited when trying to integrate it with my scenario.

Your OpenFileAsync method returns a selected IStorageFile and this one has a Name property that gets you the name of the file including the file name extension and a Path property that gets you the full file-system path of the file. You can do whatever you want with these values:
private async void OpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileClass instance = new OpenFileClass();
IStorageFile file = await instance.OpenFileAsync();
if (file != null)
{
string fileName = file.Name;
string filePath = file.Path;
}
}

Related

c# Windows form - Setup the rules for loading an image with specific filename, but recognize several extensions

I'm unsure about the right method to define some rules for a specific image in one of my user resource folders.
I allow one image in this folder with a specific name, but this single image can be a PNG / JPEG / BMP.
What could be a suitable route for loading the image as BackgroundImage, when the current code setup for loading the image would be something like this:
private void Form1_DragDrop(object sender, DragEventArgs e)
{
var data = e.Data.GetData(DataFormats.FileDrop);
if (data != null)
{
var fileNames = data as string[];
if (fileNames.Length > 0)
BackgroundImage = Image.FromFile(fileNames[0]);
BackgroundImage = Image.FromFile(#"image_default\image_default.jpg");
}
If I understand the question correctly you will have an array of filenames without extensions and you want to find that file in the directory?
You could get an Array of the files in that directory, then find the matching filename (without extension) and load from that.
var dir = System.IO.Directory.GetFiles(#"image_default\");
var imageFile = string.Empty;
foreach (string file in dir) {
if (System.IO.Path.GetFileName(file).Equals(fileNames[0]))
imageFile = file;
}
if (imageFile != null)
BackgroundImage = Image.FromFile(imageFile);
else
//some error or handle
There might be some more clever way of searching the directory without iterating through the array, but you get the idea...

How to search for a file extension (.xls) and change it's name? C#

The product I'm using is a Beijer HMI, currently i can generate a report and save it to a known location (my desktop - C:\Users\mrdav\Desktop).
I need to be able to search on my desktop for a file extension .xls and change its name.
When the report is generated by the HMI, it uses the date and time which means when the file is generated the name will be different every time.
On the press of a button i need to search my desktop for the .xls file and change its name to a variable.
// This is my variable with my program
string NewName = Globals.Tags.Tag1.Value;
The code that is generated needs to sit within the below example.
public partial class Screen1
{
void Button1_Click(System.Object sender, System.EventArgs e)
{
// Code to be added here...
}
}
Hopefully someone can help, I’m using windows compact framework so limited on functionality.
Any questions please let me know.
Thanks in advance,
Dave
Here is an example how you can do that:
DirectoryInfo dir = new DirectoryInfo(sExportPath);
FileInfo[] Files = dir.GetFiles("*.csv");
foreach(FileInfo file in Files )
{
// rename file
System.IO.File.Move(file.FullName, GenerateNewFileName());
}
//elsewhere in the class
private string GenerateNewFileName()
{
//here is where you implement creating or getting the filename that you want your file to be renamed to. An example might look like the below
string serialNumber = GetSerialNumber(); //Get the serial number that you talked about in the question. I've made it a string, but it could be an int (it should be a string)
return Path.ChangeExtension(serialNumber,".xls"); //to use path you will need a using statement at the top of your class file 'using System.IO'
}
This seems to work...but i know its not as tidy as it could be.
Any suggestions?
Thanks to all that helped, got there in the end!
void Button_Click(System.Object sender, System.EventArgs e)
{
try
{
// Location for new file
string NewFileName = #"c:\users\mrdav\desktop\testfolder\";
// Add varibale name to new file
NewFileName += Globals.Tags.Tag1.Value;
// add .xls extention to new file
NewFileName += ".xls";
//show new file name to check all ok
MessageBox.Show (NewFileName);
//search for .xls in known directory
DirectoryInfo di = new DirectoryInfo(#"c:\users\mrdav\desktop");
FileInfo[] Files = di.GetFiles("*.xls");
// if files exist with .xls extention
foreach(FileInfo file in Files )
{
// show full file name
MessageBox.Show (file.FullName);
//rename old file to new file name and move to new folder
File.Move(file.FullName, NewFileName);
}
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}

UWP, Access to the path is denied

I read some topic about file permission.
Someone said "App can access directories and files which the user manually selected with the FileOpenPicker or FolderPicker"
My codes are like as below:
public async void CsvParse()
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.FileTypeFilter.Add(".csv");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
string[] lines = File.ReadAllLines(file.Path);//this is where app stops working and gives error message.
}
}
Even when I choose file with FilePicker, it still gives me error. But when I choose file from appx folder, it works fine.
Is there a way to access other locations than app's folder?
try it this way:
public async void CsvParse()
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.FileTypeFilter.Add(".csv");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
IList<string> lines = await FileIO.ReadLinesAsync(file);//this is where app stops working and gives error message.
}
}
the StorageFile is the way you get access to a file. File.ReadAllLines(file.Path) you are passing a Filename, not the StorageFile but just the filepath is not enough for getting access

Filenames in string array c# Universal Windows

I am developing an Universal Windows Platform app.
To continue i need the filenames from all files in one folder into a string array.
The get files Method doesnt work in UWP. I tried around with The Filepicker and Storagefolder but I dont know how to get it into a string array.
// C#
FolderPicker picker= new FolderPicker();
picker.FileTypeFilter.Add("*"); StorageFolder x = await picker.PickSingleFolderAsync();
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", x);
string[] files = Directory.GetFiles(#"path\to\Assets");
textBlock.Text = files.Length.ToString();
You can use Directory.EnumerateFiles, System.IO.Path.GetFileName and LINQ :
string[] allFileNames = Directory.EnumerateFiles(dirPath)
.Select(System.IO.Path.GetFileName)
.ToArray();
I have no access to this folder. I tried with Directory.GetFiles(dirPath) and when i check for the length it says 0. These Windows Apps are Sandboxed.
Yes you are right about this, in an UWP app, we can access to the app's local folder or some special lib like Music Library in the code behind, otherwise we need to use Folder/File Picker to let user choose to access the folder/file.
I tried around with The Filepicker and Storagefolder but I dont know how to get it into a string array.
This is a correct direction and you can do this work using StorageFolder.GetFilesAsync method like this:
private string[] filename;
private async void Button_Click(object sender, RoutedEventArgs e)
{
FolderPicker picker = new FolderPicker();
picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
picker.FileTypeFilter.Add("*"); //match all the file format
StorageFolder folder = await picker.PickSingleFolderAsync();
if (folder != null)
{
var subFiles = await folder.GetFilesAsync();
filename = new string[subFiles.Count()];
for (int i = 0; i < subFiles.Count(); i++)
{
filename[i] = subFiles.ElementAt(i).DisplayName;
textBlock.Text = textBlock.Text + "+" + filename[i]; //show the file name in a textblock
}
}
}
Using picker.FileTypeFilter.Add("*") can make the filter match all type of files in the folder, but these files will not be shown in the picker interface.

Load an external textfile into a Visual studio 2012 ListView (Windows store)

I have recently been trying to load an external textfile, called KS1words.txt into a listview in Visual Studio 2012 windows store blank page, upon entering the page with the listviews. The code worked 1 day ago, but there was an error with loading files which I could not fix, so I created a new programme with the same things, and the same code that worked, now does not, I have attached it here and there is also a screenshot with the page with the ListViews. Do you have any idea what might the cause of the problem be ?
I am running this on a virtual machine !
Thank you
CODE:
private void Page_Loaded(object sender, RoutedEventArgs e)
{
FillList(#"Assets\KS1words.txt");
}
async private void FillList(string filename)
{
var KS1wordlist= new List<String>();
// this method reads line separated words from a text file and populates a List object //
Windows.Storage.StorageFolder localFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
// begin the file read operation
try
{
// open and read in the word list into an object called words
StorageFile sampleFile = await localFolder.GetFileAsync(filename);
var KS1wordsvar= await FileIO.ReadLinesAsync(sampleFile);
// add each word returned to a list of words declared
// globally as List wordList = new List();
foreach (var word in KS1wordsvar) { KS1wordlist.Add(word); }
List1.ItemsSource = KS1wordlist;
}
catch (Exception) {
// handle any errors with reading the file
}
since you are using
Windows.Storage.StorageFolder localFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
to get the folder , make sure that your text file is in the right directory.

Categories

Resources