Port from winForms to Windows phone 8.0 C# - c#

can someone help me out by porting/translating this piece of c# code wrote in winForms to Windows phone 8.0 ? Im really struggling with it and i cant make it work i probably read every single documentation that i could get my hands on but i just cant make it work. I know that stackover flow is not place where people write code for you but im hopeless.. any help is appreciated Im trying to load some info about my app from a text document and image im loading those things in array of images and array of strings. Here's the code :
private static string[] _folderPaths = Directory.GetDirectories(#"Folders");
private string[] _imagePaths;
private List<string> _questionsPaths = new List<string>();
private List<string> _correctAnswersPaths = new List<string>();
private List<string> _allAnswersPaths = new List<string>();
for (int i = 0; i < _folderPaths.Length; i++)
{
var _tempLocations = Directory.GetFiles(_folderPaths[i], (i + 1).ToString() + "*.txt*");
_imagePaths = Directory.GetFiles(_folderPaths[i], "*.png", SearchOption.TopDirectoryOnly);
foreach (string item in _tempLocations)
{
if (item == "Folders\\" + (i + 1).ToString() + "\\" + (i + 1).ToString() + ".txt")
{
_questionsPaths.Add(item);
}
if (item == "Folders\\" + (i + 1).ToString() + "\\" + (i + 1).ToString() + "answer" + ".txt")
{
_correctAnswersPaths.Add(item);
}
if (item == "Folders\\" + (i + 1).ToString() + "\\" + (i + 1).ToString() + "answers" + ".txt")
{
_allAnswersPaths.Add(item);
}
}
}

The corresponding types used in Windows Phones are (not precise mapping, of course):
Directory -> StorageFolder
Directory.GetDirectories -> StorageFolder.GetFoldersAsync
Directory.GetFiles -> StorageFolder.GetFilesAsync
So the translated code would be something like this (you need to be familiar with the new await-async keywords too)
using Windows.Storage;
var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Folders");
var subFolders = await folder.GetFoldersAsync();
foreach (StorageFolder subFolder in subFolders)
{
var tempFiles = await subFolder.GetFilesAsync(...

Related

Copy picture to folder and rename the copy with numbers from 1, sequentially

Here is all I want to do: Every time the button is clicked, an openfile dialog is opened, the user clicks on a picture, then this picture is copied to a specific folder and renamed to a number. Every picture's name in this folder should be a number, but they must all be different. My code so far:
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
int i = 0;
if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
MessageBox.Show(picturedir + "\\" + i.ToString() + ".png" + ".....Already Exists.");
}
else if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == false)
{
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Of course here, the first picture is copied and renamed to "0.png" but the next pictures are not copied at all, because the "if" gives true. Any ideas ? Thanks.
You could do this:
...
int i = 0;
while (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
// I wouldn't show that message each time, gonna get pretty old for lots of pics!
}
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
...
If you want the next number, you can enumerate the existing files, find the maximum number now in use and add 1. Something like:
var files = Directory.EnumerateFiles(myCurrentDirectory, "*.png");
var fileNumStrings = from file in files select Path.GetFileNameWithoutExtension(file);
var max = 0;
foreach (var fileNumString in fileNumStrings)
{
if (int.TryParse(fileNumString, out var filenum))
{
if (filenum > max)
{
max = filenum;
}
}
}
var nextNum = max + 1;

Excluding text files etc. from a backup application C#

private void btn_Backup_Click(object sender, EventArgs e)
{
List<DirectoryInfo> SourceDir = this.lbox_Sources.Items.Cast<DirectoryInfo>().ToList();
List<DirectoryInfo> TargetDir = this.lbox_Targets.Items.Cast<DirectoryInfo>().ToList();
foreach (DirectoryInfo sourcedir in SourceDir)
{
foreach (DirectoryInfo targetdir in TargetDir)
{
string dateString = DateTime.Now.ToString("MM-dd-yyyy_H.mm.ss");
string LogFileName = #"BackupLog_" + sourcedir.Name + #"_" + dateString + #".log";
string[] lines = { dateString + "\t" + sourcedir.FullName + "\t" + targetdir.FullName + "\t" + "COMPLETED" };
if (this.checkbox_zipfiles.Checked == true)
{
System.IO.Compression.ZipFile.CreateFromDirectory(sourcedir.FullName, targetdir.FullName + #"\BACKUP_" + sourcedir.Name + #"_" + dateString + #".zip");
System.IO.File.WriteAllLines(tbox_LogFiles.Text + #"\" + LogFileName, lines);
}
else
{
foreach (var file in sourcedir.GetFiles())
{
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(sourcedir.FullName, targetdir.FullName, true);
System.IO.File.WriteAllLines(tbox_LogFiles.Text + #"\" + LogFileName, lines);
}
}
}
}
}
I need to exclude certain files from the backup (like .txt .docx)
I am using a list on my Form to add those exceptions.
I will also need to exclude certain Files and Folders but I think I can do that if I know how to do this.
private void btn_AddFileTypeException_Click(object sender, EventArgs e)
{
Form_FileTypeExceptions frm = new Form_FileTypeExceptions(new FileException());
if (frm.ShowDialog() == DialogResult.OK)
{
this.lbox_FileTypeExceptions.Items.Add(frm.Exception);
}
}
Any ideas please?
From form where you're setting extensions to be excluded fill list of strings that will contain extensions to skip, something like this:
List<string> extensionsToSkip = new List<string>();
extensionsToSkip.Add(".txt");
extensionsToSkip.Add(".docx");
//etc...
in your inner loop, change foreach loop from
foreach (var file in sourcedir.GetFiles())
into this
foreach (var file in sourcedir.GetFiles()
.Where(f => !extensionsToSkip.Contains(f.Extension)).ToList())
as you can see, when you get file collection with GetFiles it will be filtered to exclude extensions specified in extensionsToSkip list.
before that mentioned loop, test if you're getting right number of files by observing there two lists (just for test):
var originalList = sourcedir.GetFiles();
var filteredList = sourcedir.GetFiles().Where(f => !extensionsToSkip.Contains(f.Extension)).ToList();

Permissions on a folder

I have been looking for some time now and have not been able to find this. How can I set my program up to write or update a file from multiple users but only one group is allowed to open the read what is in the folder?
class Log_File
{
string LogFileDirectory = #"\\server\boiseit$\TechDocs\Headset Tracker\Weekly Charges\Log\Log Files";
string PathToXMLFile = #"\\server\boiseit$\scripts\Mikes Projects\Headset-tracker\config\Config.xml";
string AdditionToLogFile = #"\Who.Did.It_" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Year + ".txt";
XML XMLFile = new XML();
public void ConfigCheck()
{
if (!File.Exists(PathToXMLFile))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
}
}
public void CreateLogFile()
{
if (Directory.GetFiles(LogFileDirectory).Count() == 0)
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
else if (!File.Exists(XMLFile.readingXML(PathToXMLFile)))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
else
{
FileInfo dateOfLastLogFile = new FileInfo(XMLFile.readingXML(PathToXMLFile));
DateTime dateOfCreation = dateOfLastLogFile.CreationTime;
if (dateOfLastLogFile.CreationTime <= DateTime.Now.AddMonths(-1))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
}
}
public void CreateFileOrAppend(string whoDidIt)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetStore((IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly | IsolatedStorageScope.User), null, null))
{
using (StreamWriter myWriter = new StreamWriter(XMLFile.readingXML(PathToXMLFile), true))
{
if (whoDidIt == "")
{
}
else
{
myWriter.WriteLine(whoDidIt);
}
}
}
}
This is my path where it needs to go. I have the special permission to open and write to the folder but my co workers do not. I am not allow to let them have this permission.
If I where to set up a database how would i change this code
LoggedFile.CreateFileOrAppend(Environment.UserName.ToUpper() + "-" + Environment.NewLine + "Replacement Headset To: " + AgentName + Environment.NewLine + "Old Headset Number: " + myDatabase.oldNumber + Environment.NewLine + "New Headset Number: " + HSNumber + Environment.NewLine + "Date: " + DateTime.Now.ToShortDateString() + Environment.NewLine);
I need it to pull current user, the agents name that is being affected the old headset and the new headset, and the time it took place.
While you create file, you have to set access rules to achieve your requirements. .
File.SetAccessControl(string,FileSecurity)
The below link has example
https://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol(v=vs.110).aspx
Also the "FileSecurity" class object, which is an input parameter, has functions to set access rules, including group level control.
Below link has example
https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesecurity(v=vs.110).aspx
This question will be opened under a new question since I am going to take a different route for recording the data I need Thank you all for the help

Renaming all files in folder in numeric order

i know this seems pretty simple and i know theres other questions asking this but i just need to know what im personally doing wrong and why it doesnt work because it should.
int ImageCounter = 1;
foreach (var Image in ImageFilePaths)
{
{
// Console.WriteLine(Image);
// Console.WriteLine(RenameFolderPath + #"\" + ImageCounter + ".jpeg");
File.Move(Image, RenameFolderPath + #"\" + ImageCounter + ".jpeg");
ImageCounter++;
}
}
So theres about 150 images in a folder and after running this, im left with 11, 10 of which are numbered 1-10 and the 11th is left with its original name.
if i print (image) it will print about 150 of the original names, if i print the 2nd writeline, it will print the exact same but "1 - about 150" instead of the original name. so theres no problems there, it must be with the file.move but i cannot see anything wrong
Not sure what the rest of your code looks like, but this works for me:
void Main()
{
MoveFiles(#"c:\Temp\MoveTest", #"C:\Temp\MoveTest1");
}
public void MoveFiles(string fromDir, string toDir)
{
int ImageCounter = 1;
// Take a snapshot of the file system.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(fromDir);
IEnumerable<System.IO.FileInfo> ImageFilePaths = dir.GetFiles("*.*", System.IO.SearchOption.TopDirectoryOnly);
foreach (var Image in ImageFilePaths)
{
{
Console.WriteLine(Image);
Console.WriteLine(toDir + #"\" + ImageCounter + ".jpeg");
File.Move(Image.FullName, toDir + #"\" + ImageCounter + ".jpeg");
ImageCounter++;
}
}
}

File transfer error

I'm making an application, and at some point it does the following: Checks if a file that will be created, already exists in a directory (output), if it exists, he sends for the Errors folder, if not, it sends to the output folder. But comes a point where the program transfers the file to the folder errors, and buga, saying that the file does not exist, for example, he just transfer it t file (49) .png, and he again read the same file ! Funny is only in some cases it
if (System.IO.File.Exists(entrada + "t (" + i + ").png")){
string[] datas1 = Spire.Barcode.BarcodeScanner.Scan(#"C:\\QTRACK\\Entrada\\PNG\\t (" + i + ").png");
this.textBox1.Text = datas1[0];
foreach (string code in datas1)
{
DirectoryInfo exit = new DirectoryInfo(#"C:/QTRACK/Erro/");
FileInfo[] teste = exit.GetFiles("*.png");
x = teste.Length +1;
for (c = x; c <= 1000000000; c++)
{
if (System.IO.File.Exists(saida + code + ".png"))
{
System.IO.File.Move(entrada.ToString() + "t (" + i + ").png", erro + "e" + c + ".png");
}
else
{
System.IO.File.Move(entrada.ToString() + "t(" + i + ").png", saida + code + ".png");
}
}
}
}
else
{
}
}
}
It gives the error FileNotFoundExecption, however, was himself who changed the file and're trying to change again. Please help.

Categories

Resources