I have a problem with Process.Start(), i want it to open specified file when I double click on tree node.
This is my code where it should open file
String path = "C:\\Users\\........\\something";
private void treePrica_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
{
try {
String TreeNodeName = treePrica.SelectedNode.ToString().Replace("TreeNode: ", String.Empty);
MessageBox.Show(this.path + "\\" + TreeNodeName);
Process.Start(this.path + "\\" + TreeNodeName);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
When i double click on any of the nodes containing .txt file it throws exception like this
just use string path = #"c:/something"; and make sure you add the extension to the total path!
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 have to do transfer files from one host to other so i have decided to go with zip (IONIC) but problem with that is it eat's lot of memory when it comes for larger file, so i have decided to go with 7Z dll. i had tried to achieve compress & Uncompress which works perfectly fine on my console after changing some settings (unchecked prefer-32 bit from https://blog.jongallant.com/2011/10/7-zip-dll-file-does-not-exist/).
but which fails on ASP.net application and i am getting "Can not load 7-zip library or internal COM error! Message: failed to load library." when i try to compress or uncompress.
the code what i have tried.
protected void btnCompress_Click(object sender, EventArgs e)
{
var dllPath = "";
if (Environment.Is64BitOperatingSystem)
{
dllPath = HttpContext.Current.Server.MapPath(#"7z\7z64.dll");
}
else
dllPath = HttpContext.Current.Server.MapPath(#"7z\7z.dll");
var tmpPath = System.IO.Path.Combine(txtTempPath.Text, txtDir.Text);
try
{
SevenZip.SevenZipCompressor.SetLibraryPath(dllPath);
SevenZipCompressor sz = new SevenZipCompressor();
sz.CompressionLevel = CompressionLevel.Ultra;
sz.CompressionMode = CompressionMode.Create;
sz.CompressionMethod = CompressionMethod.Default;
sz.FastCompression = true;
sz.CompressDirectory(tmpPath, tmpPath + "_7Zip.7z");
//Directory.Delete(backupFolder, true);
Response.Write("<script>alert('Compressed successfully');</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
//throw ex;
}
}
protected void btnExtract_Click(object sender, EventArgs e)
{
try
{
var tmpPath = System.IO.Path.Combine(txtTempPath.Text, txt7z.Text);
SevenZipExtractor.SetLibraryPath(#"C:\Program Files\7-Zip\7z.dll");
SevenZipExtractor zip = new SevenZipExtractor(tmpPath);
zip.ExtractArchive(System.IO.Path.GetFileNameWithoutExtension(tmpPath));
Response.Write("<script>alert('Extracted successfully');</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
please someone suggest a proper solution for this,
Thanks in Advance.
I think using (Environment.Is64BitProcess) instead of Environment.Is64BitOperatingSystem) will work if you have set correct dll path.Make sure that dll exists in that path.
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.
I am trying to open a file from a ListView control on a Windows Form project in C#.
I've created the ItemActivate event on the selected item of the ListView control and verified that it works properly by adding a MessageBox.Show().
I want to add to the ItemActivate event code to open the selected item if it is a file object.
// store current directory
string currentDir = Directory.GetCurrentDirectory();
private void browserListView_ItemActivate(object sender, EventArgs e)
{
string selectedFile = browserListView.SelectedItems[0].Text;
// the file exists open the file.
if (File.Exists( Path.Combine( currentDir, selectedFile ) ) )
{
//
try
{
MessageBox.Show(currentDir + #"\" + selectedFile);
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
}
}
What do I need to add to the try block to replace the MessageBox.Show line in order to launch the selected file from my control?
Thanks for the comments, the Systems.Diagnostics.Process.Start is what I was looking for.
private void browserListView_ItemActivate(object sender, EventArgs e)
{
string selectedFile = browserListView.SelectedItems[0].Text;
// If it's a file open it
if (File.Exists( Path.Combine( currentDir, selectedFile ) ) )
{
//MessageBox.Show(currentDir + #"\" + selectedFile);
try
{
System.Diagnostics.Process.Start(currentDir + #"\" + selectedFile);
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
}
}
System.Diagnostics.Process.Start(Path.Combine(currentDir, selectedFile));
I'm developing a WinForms application using C# with an OpenFileDialog and FileBrowserDialog and I'd like to:
Enable selection of multiple xls files.
After selection is made, Display selected xlsx filenames in textbox
Copy the selected files to a separate directory Consolidated
How can I accomplish this?
Here is sample code:
OpenFileDialog od = new OpenFileDialog();
od.Filter = "XLS files|*.xls";
od.Multiselect = true;
if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string tempFolder = System.IO.Path.GetTempPath();
foreach (string fileName in od.FileNames)
{
System.IO.File.Copy(fileName, tempFolder + #"\" + System.IO.Path.GetFileName(fileName));
}
}
There is MultiSelect property of OpenFileDialog which you need to set to true to allow selecting multiple files.
Here is a code example from MSDN which allows the user to select a multiple number of images and display them in PictureBox controls on a Form:
private void Form1_Load(object sender, EventArgs e)
{
InitializeOpenFileDialog();
}
private void InitializeOpenFileDialog()
{
// Set the file dialog to filter for graphics files.
this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
"All files (*.*)|*.*";
// Allow the user to select multiple images.
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "My Image Browser";
}
private void selectFilesButton_Click(object sender, EventArgs e)
{
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
// Read the files
foreach (String file in openFileDialog1.FileNames)
{
// Create a PictureBox.
try
{
PictureBox pb = new PictureBox();
Image loadedImage = Image.FromFile(file);
pb.Height = loadedImage.Height;
pb.Width = loadedImage.Width;
pb.Image = loadedImage;
flowLayoutPanel1.Controls.Add(pb);
}
catch (SecurityException ex)
{
// The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
"Error message: " + ex.Message + "\n\n" +
"Details (send to Support):\n\n" + ex.StackTrace
);
}
catch (Exception ex)
{
// Could not load the image - probably related to Windows file system permissions.
MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
+ ". You may not have permission to read the file, or " +
"it may be corrupt.\n\nReported error: " + ex.Message);
}
}
}
Combining both answers, here's the code I came up with to:
Enabling the user to Select Multiple XLSX Files (using MultiSelect, OpenFileDialog, this.OpenFileDialog Properties & FileBrowserDialog)
After selection is made, Display Selected XLSX Filenames in Textbox (by setting textBoxSourceFiles.Text value to sourceFileOpenFileDialog.FileNames)
Copy the Selected Files to a separate Consolidated directory (using foreach loop, System.IO.File.Copy, System.IO.Path.GetFileName, sourceFileOpenFileDialog.FileName)
private void sourceFiles_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog sourceFileOpenFileDialog = new OpenFileDialog();
this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|All Files (*.*)|*.*";
this.sourceFileOpenFileDialog.FilterIndex = 2;
this.sourceFileOpenFileDialog.RestoreDirectory = true;
this.sourceFileOpenFileDialog.Multiselect = true;
this.sourceFileOpenFileDialog.Title = "Please Select Excel Source File(s) for Consolidation";
if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
{
using (myStream)
{
// populates text box with selected filenames
textBoxSourceFiles.Text = sourceFileOpenFileDialog.FileNames;
}
} // ends if
} // ends try
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
} // ends if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
} // ends public void sourceFiles_Click
private void consolidateButton_Execute_Click(object sender, EventArgs e)
{
string consolidatedFolder = targetFolderBrowserDialog.SelectedPath;
foreach (String file in sourceFileOpenFileDialog.FileNames)
{
try
{
// Copy each selected xlsx files into the specified TargetFolder
System.IO.File.Copy(sourceFileOpenFileDialog.FileName, consolidatedFolder + #"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
Log("File" + sourceFileOpenFileDialog.FileName + " has been copied to " + consolidatedFolder + #"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
}
} // ends foreach loop
} // ends void consolidateButton_Execute_Click