Isolated storage in windows phone 7 - c#

I am trying to do a check on the isolated storage followed by some command along with it.
What i wanted was to check for directories name consisting "a*"
*If the directories exist* it will check if the diretory named after "a + today date" exist.
If it exist will show up a pop up message telling it does exist.
But if no directories consisting of "a*" is exist at all it will show a message of "Does not exist".
Below is my code:
Is able to check if the directories exist when there is a directory of "a*" is created.
But it does not work *when none of the directories "a" is created**.
How should i modify my code?
Code:
string[] fileNames;
string selectedFolderName;
private void gameBtn_Click(object sender, RoutedEventArgs e)
{
//MediaPlayer.Stop();
string currentDate = DateTime.Now.ToString("MMddyyyy");
string currentDateName = "a" + currentDate;
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
fileNames = myStore.GetDirectoryNames("a*");
foreach (var name in fileNames)
{
if (fileNames.Contains(currentDateName))
{
selectedFolderName = currentDateName;
MessageBox.Show("Your schedule for today");
NavigationService.Navigate(new Uri("/DisplaySchedule.xaml?selectedFolderName=" + selectedFolderName, UriKind.Relative));
}
else
{
MessageBox.Show("No Schdule for today", "Schedule Reminder", MessageBoxButton.OK);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
}
}

Your error is just a simple typo.
if (fileNames.Contains(currentDateName))
should be
if (name.Contains(currentDateName))
As for handling when there's no directory "a*", check if fileNames is empty.
if (fileNames.Length == 0) // no Directory 'a' was found, create it
{
// create code here
}

Related

Persisting file path between runs in c#

I have an app in which the user needs to access certain files in a user set and selected folder.
The folder and files paths need to be easily accessed (short simple path).
I use the Properties Settings to hold the Folder and File paths, but for some reason each time I re-start the program the Folder and File paths are lost.
I have followed and checked the program and all seems to be OK (except something I am missing, apparently).
I attach here the program snippet in two parts: The search for path and the setting in case path / file not found. (removed exception handling to save on lines)
public Main() //part of Main, stripped off exception handling)
{
//..........
dataFolder = Properties.Settings.Default.dataFolder;
if (!Directory.Exists(dataFolder))
{
SetDataFolder();
}
configFile = Properties.Settings.Default.configFile;
if (!File.Exists(configFile))
{
SetConfigFile();
}
dataFile = Properties.Settings.Default.dataFile;
if (!File.Exists(dataFile))
{
SetDataFile();
}
loadParamsFromFile(configFile); //Load the previously saved controls.
public String SetDataFolder()
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
DialogResult folder = dialog.ShowDialog();
if (folder == DialogResult.OK)
{
dataFolder = dialog.SelectedPath;
Directory.CreateDirectory(dataFolder);
dataFolder = Path.GetFullPath(dataFolder);
Properties.Settings.Default.dataFolder = dataFolder;
Properties.Settings.Default.Save();
return dataFolder;
}
else return null;
}
private string SetDataFile()
{
dataFile = $"{dataFolder}\\{textBoxSampleID.Text.Replace("/r", "").Trim()}.txt";
File.Create(dataFile).Close();
Properties.Settings.Default.dataFile = dataFile;
Properties.Settings.Default.Save();
return dataFile;
}
private string SetConfigFile()
{
configFile = $"{dataFolder}\\electroplating.cfg";
File.Create(configFile).Close();
Properties.Settings.Default.configFile = configFile;
Properties.Settings.Default.Save();
return configFile;
}
Check out this question:
How to change application settings (Settings) while app is open?
I would suggest using Path.Combine() for the construction of the file paths.
If it still doesn't work, you could also try using the registry for storing the values.
string dataFilePath = Path.Combine(dataFolder, textBoxSampleID.Text.Replace("/r", "").Trim());
RegistryKey key = Registry.LocalMachine.CreateSubKey(#"SOFTWARE\Company");
if (key != null)
{
key.SetValue("dataFilePath", dataFilePath);
}
You could then use string dataFilePath = (string)key.GetValue("dataFilePath") to get the value out of the registry.

Can't get directory from external device

I'm trying to get the items from within a folder on an Android phone.
However the FolderBrowserDialog won't let me select a folder from within in the phone. The path looks like this This PC\Xperia Z3 Compact\SD Card\Music
To select a folder I'm currently using:
private void button_Click(object sender, EventArgs e)
{
System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
UserFolderLocation = dlg.SelectedPath;
}
else { }
}
Then when searching the folder for its contents I use:
try
{
folderItems = Directory.GetFiles(directory).Select(f => Path.GetFileNameWithoutExtension(f)).ToArray();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
If I insert the path This PC\Xperia Z3 Compact\SD Card\Music as a variable then search it, it throws a System.IO.DirectoryNotFoundException.
How do I select and use a path that doesn't begin with c:, d: etc?
In the end I ended up using the shell32 library. It has the ability to handle portable devices (That both include and don't include the drive letters).
Include the reference for shell32.dll
and include the library:
using Shell32;
Then instead of using the FolderBrowserDialog I used the use the shell browse for folder. Which returns a strange path for a folder on a phone, for the phone I used to test the path looked like this:
::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\\?\usb#vid_04e8&pid_6860&ms_comp_mtp&samsung_android#6&fee689d&3&0000#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\SID-{20002,SECZ9519043CHOHB01,63829639168}\{013C00D0-011B-0130-3A01-380113012901}
public int Hwnd { get; private set; }
private void button3_Click(object sender, EventArgs e)
{
Shell shell = new Shell();
Folder folder = shell.BrowseForFolder((int)Hwnd, "Choose Folder", 0, 0);
if (folder == null)
{
// User cancelled
}
else
{
FolderItem fi = (folder as Folder3).Self;
UserFolderLocation = fi.Path;
}
}
Then to select search the folder for its contents:
try
{
Folder dir = shell.NameSpace(directory);
List<string> list = new List<string>();
foreach (FolderItem curr in dir.Items())
{
list.Add(curr.Name);
}
folderItems = list.ToArray();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
"This PC" is only there for the eyes of the user - internally it is not used at all. You can see for yourself by applying the first marked setting in Windows Explorer
Additionally Windows assigns a drive letter to every local device - it just doesn't show it by default. (use the second marked setting to check)
So in reality you have to use (assuming you phone was assigned Drive F:) something like F:\SD Card\Music\.
Possibly related: Get List Of Connected USB Devices about the ability to find a device without knowing the assigned drive letter.

Error Access to the path is denied when Rename a Directory

I want to rename the a folder with the new name inputed in a Textbox txtFilenFolderName:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string[] values = EditValue;
string oldpath = values[0];// = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder"
string oldName = values[2]; //= New Folder
string newName = txtFilenFolderName.Text; //= New Folder1
string newPath = string.Empty;
if (oldName != newName)
{
newPath = oldpath.Replace(oldName, newName);
Directory.Move(oldpath, newPath);
}
else
lblmessage2.Text = "New name must not be the same as the old ";
}
}
Try to debug:
oldpath = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder"
oldName = New Folder
newName= New Folder1
newpath = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder1"
Everything seems right, but I when I click on buton Edit ---> rename---> Update---> an error occur: Access to the path is denied D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder
Help!
the path "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder" probably doesn't exist. I'm thinking you meant "D:\C#Projects\website\Lecturer\giangvien\New folder". I think what #CharmingInferno was trying to get at was that when you use # in front of a string you don't need to use escape characters as it takes the text as is like the following
string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt
string h = #"\\server\share\file.txt"; // \\server\share\file.txt
However you are putting your values in the EditValue string array should be corrected.
I had the same problem just now.
Using
Directory.Move(srcDirectory, dstDirectory);
sometimes caused the Access to the path /dstDirectory/ is denied exception, sometimes it don't.
The following solved for me.
new DirectoryInfo(srcDirectory).MoveTo(dstDirectory);

Getting name(s) of FOLDER containing a specific SUBSTRING from the C:Temp directory in C#

Guys as the title says it I have to get the names of FOLDERS having a particular (user indicated) sub string.
I have a text box where the user will input the wanted sub string.
and I am using the codes below to achieve my goal.
string name = txtNameSubstring.Text;
string[] allFiles = System.IO.Directory.GetFiles("C:\\Temp");//Change path to yours
foreach (string file in allFiles)
{
if (file.Contains(name))
{
cblFolderSelect.Items.Add(allFiles);
// MessageBox.Show("Match Found : " + file);
}
else
{
MessageBox.Show("No files found");
}
}
It does not work.
When I trigger it,only the message box appears.
Help ?
You can use the appropriate API to let the framework filter the directories.
var pattern = "*" + txtNameSubstring.Text + "*";
var directories = System.IO.Directory.GetDirectories("C:\\Temp", pattern);
Because the MessageBox will appear for the first path that does not contain the substring
You could use Linq to get the folders, but you will need to use GetDirectories not GetFiles
string name = txtNameSubstring.Text;
var allFiles = System.IO.Directory.GetDirectories("C:\\Temp").Where(x => x.Contains(name));//
if (!allFiles.Any())
{
MessageBox.Show("No files found");
}
cblFolderSelect.Items.AddRange(allFiles);
You don't want to have the message box inside the loop.
string name = txtNameSubstring.Text;
string[] allFiles = System.IO.Directory.GetFiles("C:\\Temp");//Change path to yours
foreach (string file in allFiles)
{
if (file.Contains(name))
{
cblFolderSelect.Items.Add(file);
// MessageBox.Show("Match Found : " + file);
}
}
if(cblFolderSelect.Items.Count==0)
{
MessageBox.Show("No files found");
}
(Assuming cblFolderSelect was empty before this code runs)
As you currently have it, you're deciding whether to show the message box for each file that you examine. So if the first file doesn't match, you'll be told "No files found" even though the next file might match.
(I've also changed the Add to add the individual file that matches, not all of the files (for which one or more matches))

File.Exists -- do NOT want to create new file

I'm new to coding - so bear with me. I've done a lot of reading and can't figure this one out.
So when you run my new the app, you type in a folder name. The app goes to that folder, then will scan through 2 different log files that are in this designated folder. BUT here is where I'm getting in trouble. If the log does NOT exist - it will ask if you want to create the file that it is looking for... I do NOT want it to do that. I would just like it to go to the folder, if the file does not exist then do nothing and move on to the next line of code.
Here is the code I have so far:
private void btnGo_Click(object sender, EventArgs e)
{
//get node id from user and build path to logs
string nodeID = txtNodeID.Text;
string serverPath = #"\\Jhexas02.phiext.com\rwdata\node\";
string fullPath = serverPath + nodeID;
string dbtoolPath = fullPath + "\\DBTool_2013.log";
string msgErrorPath = fullPath + "\\MsgError.log";
//check if logs exist
if (File.Exists(dbtoolPath) == true)
{
System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}
{
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}
The app will display The 2013 DBTool log does not exist for this Node. - then it opens Notepad and asks me if it wants to create the file.
Cannot find the \\Jhexas02.phiext.com\rwdata\node\R2379495\DBTool_2013.log file.
Do you want to create a new file?
I DO NOT want to create a new file, ever. Any good ways to get around this?
You skipped "Else" after "if"
if (File.Exists(dbtoolPath) == true)
{
System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}
else
{
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}
While your code compiles (it's valid to just add bracers like that) it could be as simple as adding else to your if statement:
if (File.Exists(dbtoolPath) == true) // This line could be changed to: if (File.Exists(dbtoolPath))
{
System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}
else // Add this line.
{
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}
As your code looks now, this part will always run:
{
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}
It's essentially the same as this code:
if (File.Exists(dbtoolPath) == true)
{
System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
try this :
if (File.Exists(dbtoolPath))
{
System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}
else {
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}

Categories

Resources