screenshot
So this is a method that gets the directory of a file (is a .JDCEDFile but its is just renamed .zip file)
With this method i try to rename het file and extract it to a specified folder.
And show its contents into the right textboxes.
This method fails at Extracting process and i don't understand why.
public void OpenEncodedFile(string path)
{
// Variabelen + verwerking
string defaultpath = Application.StartupPath + #"\temp";
string defaultzip = path;
string defaultzipRename = defaultzip.Replace(".JDCEDFile", ".zip");
File.Move(defaultzip, defaultzipRename);
ZipFile.ExtractToDirectory(defaultzipRename, defaultpath);
Input.Text = File.ReadAllText(defaultpath + #"\tempData.txt");
Password.Text = File.ReadAllText(defaultpath + #"\tempPass.txt");
File.Move(defaultzipRename, defaultzip);
}
"path" has to be wrong, I just tested it and it worked fine.
private void openEncodedFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openEncodedFileDialog.ShowDialog() == DialogResult.OK)
{
OpenEncodedFile(openEncodedFileDialog.FileName);
}
}
This the the code.
Related
I have a c# script in VS 2019 and now I want to write values to a File but where do Ihave to put the .txt file? After that I want to make a Setup.exe with Inno Setup Compiler.
So my question is where do I put the file to get access to it during programming my Programm and after I installed my .exe after I installed it from the Setup.exe.
I heard something about this but I dont know what this does:
string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "combinations.txt");
Now i set the Permission on top of the function as it was mention here but i still get the problem
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private void button4_Click(object sender, EventArgs e)
{
string date = DateTime.Now.ToString("g");
string exePath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
string logFile = "combinations.txt";
if (File.Exists(Path.Combine(exePath, logFile)) == false)
File.Create(Path.Combine(exePath, logFile));
using (StreamWriter wr = File.AppendText(Path.Combine(exePath, logFile)))
{
wr.WriteLine(date + "|" + date);
wr.Close();
}
}
Thanks for your help
i think you can use this path correctly
it's in the folder where your exe works.
for example a writing log file in the exe folder.
in debug mode its in the debug folder.
public static void LogWrite(string mes)
{
string exepath= Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
DateTime _dt = DateTime.Now;
string logFile= "Log.Inc";
if (File.Exists(Path.Combine(exepath, logFile)) == false)
File.Create(Path.Combine(exepath, logFile));
using (StreamWriter wr = File.AppendText(Path.Combine(exepath, logFile)))
{
wr.WriteLine(_dt.ToString("dd/MM/yyyy") + "|" + _dt.ToString("hh:mm") + "|" + mes);
wr.Close();
}
}
Based on my test, you can try try the following code to log the information to the txt file when you have published it.
private void button1_Click(object sender, EventArgs e)
{
string date = DateTime.Now.ToString("g");
string exePath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
string logFile = "combinations.txt";
using (StreamWriter wr = new StreamWriter(Path.Combine(exePath, logFile), true))
{
wr.WriteLine(date + "|" + date);
wr.Close();
}
string path = Path.Combine(exePath, logFile);
MessageBox.Show(path);
}
If you use the above code, there is no need to check if the file is created.
Also, I show the path of the txt file in the final code.
i'm stuck with my program in c#. So the user has to press a button to create a random string (working fine) he can then chose to click on the other button. this one opens a filedialog and let him chose a dll file he want to rename into the random string. i can't get it working. it says my dll is already running in another process (wich is not). Any help is greatly appreciated :)
private void btnEncrypt_Click_1(object sender, EventArgs e)
{
// sets a random string to txtEncrypt.text
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog MyOpenFileDialog = new OpenFileDialog();
//filedialog
MyOpenFileDialog.Filter = "dll files (*.dll) |*.dll";//filter
MyOpenFileDialog.Title = "Chose the dll file";
MyOpenFileDialog.InitialDirectory = "C:\\Users\\Gebruiker\\Desktop";
MyOpenFileDialog.FilterIndex = 1;
MyOpenFileDialog.RestoreDirectory = true;
//if ok
if (MyOpenFileDialog.ShowDialog() == DialogResult.OK)
{
strPath = MyOpenFileDialog.FileName;
StreamReader reader = new StreamReader(strPath);
System.IO.File.Move(strPath, "C:\\Users\\Gebruiker\\Desktop\\" + txtEncrypt.Text + ".dll");
}
else //cancel
{
strPath = null;
}
It's because your StreamReader is opening the file so it can't be moved. That line doesn't appear to be doing anything anyway so you can probably remove it. Ideally replace it with
if (System.IO.File.Exists(strPath))
{
System.IO.File.Move(strPath, "C:\\Users\\Gebruiker\\Desktop\\" + txtEncrypt.Text + ".dll");
}
Just comment the initialization of the streem reader line or move it next to the rename line but don't forget to pass the new name
Application I'm making give user ability to drag picture onto it and then copy this image to several folders at once.
Everything works great when I use local file, but I can't make it work with images dragged from internet browser directly on form.
Sure, image is saved in correct folders but name is changed to gibberish with .bmp extension.
So for example when I drag 100kb image with name "image.jpg" from browser I get 3mb image with name "sInFeER.bmp". I'm testing it on Firefox. I know I'm actually copying image from browser temp folder when I do that and file name is already changed there.
How can I keep correct file name and extension in this situation? (and preferably get image NOT converted to huge bmp file...)
Code I'm using for testing:
private void button10_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
e.Effect = DragDropEffects.All;
}
}
private void button10_DragDrop(object sender, DragEventArgs e)
{
string[] draggedFiles = (string[])e.Data.GetData(DataFormats.FileDrop, false);
CatchFile(0, draggedFiles);
}
private void CatchFile(int id, string[] draggedFiles)
{
string directory = #”C:\test\”;
foreach (string file in draggedFiles)
{
Directory.CreateDirectory(directory);
File.Copy(file, directory + Path.GetFileName(file));
MessageBox.Show(Path.GetFileName(file)); // test
}
}
Thanks for all answers.
I've done some reading and decided that accessing original image when dragging from browser (Firefox) is pretty much impossible (without use of Firefox API), so I just used WebClient.DownloadFile to download dropped picture.
Here is code I ended with:
private void button10_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
e.Effect = DragDropEffects.All;
}
}
private void button10_DragDrop(object sender, DragEventArgs e)
{
string draggedFileUrl = (string)e.Data.GetData(DataFormats.Html, false);
string[] draggedFiles = (string[])e.Data.GetData(DataFormats.FileDrop, false);
CatchFile(draggedFiles, draggedFileUrl);
}
private void CatchFile(string[] draggedFiles, string draggedFileUrl)
{
string directory = #"C:\test\";
foreach (string file in draggedFiles)
{
Directory.CreateDirectory(directory);
if (string.IsNullOrEmpty(draggedFileUrl))
{
if (!File.Exists(directory + Path.GetFileName(file))) File.Copy(file, directory + Path.GetFileName(file));
else
{
MessageBox.Show("File with that name already exists!");
}
}
else
{
string fileUrl = GetSourceImage(draggedFileUrl);
if (!File.Exists(directory + Path.GetFileName(fileUrl)))
{
using (var client = new WebClient())
{
client.DownloadFileAsync(new Uri(fileUrl), directory + Path.GetFileName(fileUrl));
}
}
else
{
MessageBox.Show("File with that name already exists!");
}
}
// Test check:
if (string.IsNullOrEmpty(draggedFileUrl)) MessageBox.Show("File dragged from hard drive.\n\nName:\n" + Path.GetFileName(file));
else MessageBox.Show("File dragged frow browser.\n\nName:\n" + Path.GetFileName(GetSourceImage(draggedFileUrl)));
}
}
private string GetSourceImage(string str)
{
string finalString = string.Empty;
string firstString = "src=\"";
string lastString = "\"";
int startPos = str.IndexOf(firstString) + firstString.Length;
string modifiedString = str.Substring(startPos, str.Length - startPos);
int endPos = modifiedString.IndexOf(lastString);
finalString = modifiedString.Substring(0, endPos);
return finalString;
}
There is probably better way of doing that but this works for me. Doesn't seem to work with other browsers. (but I needed it only to work with Firefox so I don't care)
Looks like you were dragging pixels from firefox to your app, not the url. I would look on the mozilla site for more info on how to drag the url to your app. They have lots of programming stuff and APIs to interact with the browser.
Currently having an issue when saving a merged word. doc to a specific location using a filebrowser dialog
// input destintion
private string[] sourceFiles;
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
sourceFiles = Directory.GetFiles(selectedFolder, "*.doc");
}
}
// output destintion
private string[] sourceFileOutput;
private void browseButtonOut_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowserOutput = new FolderBrowserDialog();
diagBrowserOutput.Description = "Select a folder location to save the document...";
// Default folder, altered when the user selects folder of choice
string outputFolder = #"";
diagBrowserOutput.SelectedPath = outputFolder;
// output file path display
outputPath.Text = diagBrowserOutput.SelectedPath;
if (DialogResult.OK == diagBrowserOutput.ShowDialog())
{
outputFolder = diagBrowserOutput.SelectedPath;
outputPath.Text = diagBrowserOutput.SelectedPath;
sourceFileOutput = Directory.GetFiles(outputFolder);
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (sourceFiles != null && sourceFiles.Length > 0)
{
string outputFileName = (sourceFileOutput + "Combined.docx");
MsWord.Merge(sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
// Message displaying error.
MessageBox.Show("Please a select a relevant folder with documents to combine", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
instead of getting the 'combined.docx' in the location chosen, i instead get a file called 'System.String[]Combined' saved on the desktop. Obviously there is something clashing regarding the name and the user selected file path.
i currently have the input folder options working however the output + file name doesn't seem to be working correctly.
any suggestions or help would be greatly appreciated, thank you.
string outputFileName = (sourceFileOutput + "Combined.docx");
This should probably read
string outputFileName = selectedFolder + "Combined.docx";
That said, please use Path.Combine to combine two parts of a path.
got the program to use the 'selected' destination.
// output destintion
string outputFolder = #"";
private void browseButtonOut_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowserOutput = new FolderBrowserDialog();
diagBrowserOutput.Description = "Select a folder location to save the document...";
// Default folder, altered when the user selects folder of choice
diagBrowserOutput.SelectedPath = outputFolder;
// output file path display
outputPath.Text = diagBrowserOutput.SelectedPath;
if (DialogResult.OK == diagBrowserOutput.ShowDialog())
{
outputFolder = diagBrowserOutput.SelectedPath;
outputPath.Text = diagBrowserOutput.SelectedPath;
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (sourceFiles != null && sourceFiles.Length > 0)
{
string folderFolder = outputFolder;
string outputFile = "Combined.docx";
string outputFileName = Path.Combine(folderFolder, outputFile);
MsWord.Merge(sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
i used the path.combine as suggested, as played around with the variables i had used.
I have this backup and restore code in C# using MS Access as its database. I finished doing the backup in zip format and now I want to restore the Zipped file. Any help will be much appreciated.
public void BackupDatabase(string dateToday)
{
string dbFileName = "dbCPS.accdb";
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory , dbFileName);
string backTimeStamp = Path.GetFileNameWithoutExtension(dbFileName) + "_" + dateToday + ".zip";// +Path.GetExtension(dbFileName);
string destFileName = backTimeStamp;// +dbFileName;
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
string PathtobackUp = fbd.SelectedPath.ToString();
destFileName = Path.Combine(PathtobackUp, destFileName);
//File.Copy(CurrentDatabasePath, destFileName, true);
using (var zip = new ZipFile())
{
zip.AddFile(dbFileName);
zip.Save(destFileName);
}
MessageBox.Show("Backup successful! ");
}
}
private void backupToolStripMenuItem1_Click(object sender, EventArgs e)
{
BackupDatabase(DateTime.Now.ToString("ddMMMyyyy_HH.mm"));
}
public void RestoreDatabase(string restoreFile)
{
string dbFileName = "dbCPS.accdb";
string pathBackup = restoreFile;
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory, dbFileName);
File.Copy(pathBackup, CurrentDatabasePath, true);
MessageBox.Show("Restore successful! ");
}
private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
openFileDialogBackUp.FileName = "dbCPS";
openFileDialogBackUp.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + #"Sauvegardes";
if (openFileDialogBackUp.ShowDialog() == DialogResult.OK)
RestoreDatabase(openFileDialogBackUp.FileName);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
This code extracts the zipped file but I dont know how to do the restore at the same time.
using (ZipFile zip = ZipFile.Read(restoreFile))
{
zip.ExtractAll(#"C:\Users\Desktop\backup");
}
According to the MSDN documentation here, you should be able to extract the zip file directly to the destination folder. Your existing "restore" code simply does a file copy to CurrentDatabasePath, so one would expect that a statement like...
System.IO.Compression.ZipFile.ExtractToDirectory(pathToZipFile, CurrentDatabasePath);
...would be all it takes. (I would test it myself, but ZipFile was apparently added in .NET 4.5 and my copy of Visual Studio is too old.)