Extract resources to current directory? - c#

I want to extract the resources "cygz.dll" to the current directory where the program started right after the form is loaded.
Here is my code.
private static void extract(string nameSpace, string outDirectory, string internalFilePath, string resourceName)
{
Assembly assembly = Assembly.GetCallingAssembly();
using (Stream s = assembly.GetManifestResourceStream(nameSpace + "." + (internalFilePath == "" ? "" : internalFilePath + ".") + resourceName))
using (BinaryReader r = new BinaryReader(s))
using (FileStream fs = new FileStream(outDirectory + "\\" + resourceName, FileMode.OpenOrCreate))
using (BinaryWriter w = new BinaryWriter(fs))
w.Write(r.ReadBytes((int)s.Length));
}
private void Form1_Load(object sender, EventArgs e)
{
extract("myNamespace", "\\TEMP", "resources", "cygz.dll");
}
Instead of "\\TEMP", I want to extract "cygz.dll" to the current directory

If by "current directory" you mean the path for the executable file that started the application, then you can use Application.ExecutablePath like this:
System.IO.Path.GetDirectoryName(Application.ExecutablePath);
You can find more details here: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.application.executablepath?view=netframework-4.7.2

This solved my problem
private void Form1_Load(object sender, EventArgs e)
{
string path = Environment.CurrentDirectory;
extract("myNamespace", path, "resources", "cygz.dll");
}

Related

System.IO.FileNotFoundException "Could not find file" even after manually typing file Path

I tried to use the method
System.IO.File.Move(sourceFile,newFilePath);
to rename a File, but I always get the same error message, that my file couldn't be found.
I tried to manually write the source Path
System.IO.File.Move(#"D:\Users\XXX\Desktop\TestOrHMoin",#"D:\Users\XXX\Desktop\TestOrHMoinNEW");
but I still get the same ERROR Message.
This is my full code
`
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog = new OpenFileDialog();
if (openfiledialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
oldFilePath = openfiledialog.FileName;
listBox1.Items.Add(oldFilePath);
}
}
private void button2_Click(object sender, EventArgs e)
{
newFilePath = textBox1.Text;
oldFilePath = oldFilePath.Remove(oldFilePath.Length-newFilePath.Length);
newFilePath = oldFilePath + newFilePath;
string sourceFile = #oldFilePath;
string newFile = #newFilePath;
MessageBox.Show(sourceFile);
System.IO.File.Move(sourceFile,newFilePath);
// This part is the real code, the above Part is for debugging/testing
//System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile);
//if (fi.Exists)
//{
// fi.MoveTo(newFilePath);
// MessageBox.Show("Erfolgreich geƤndert");
//} else { MessageBox.Show("Abbruch"); }
}
`
oldFilePath = oldFilePath.Remove(oldFilePath.Length-newFilePath.Length);
was wrong
I needed to declare another variable, so oldFilePath gets untouched. It was my error. I still don't know, why the manuell direction got an error.

Create and write into the txt file with one button

I would like to create the txt file that has name from my textbox1 and at the same time, I would like to write in it text from my textbox2.
Can you help me?
I have tried this
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\Users\felc\Desktop\file\" + textBox1.Text +
".txt";
File.Create(path);
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(textBox1.Text);
}
}
I would suggest you first check if the file already exists, and only create it if not.
Something like:
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\Users\felc\Desktop\file\" + textBox1.Text + ".txt";
if (!File.Exists(path))
{
File.Create(path);
}
using(var tw = new StreamWriter(path, false))
{
tw.WriteLine(textBox2.Text);
}
}
Note : in case you would like your code to append line to the file and not to re-write it, change the secont argument to "true": new StreamWriter(path, true)
Note 2 : You wrote the value of the first text box to the file instead of the second one. hence, in your code the text in the file will be the same as it's name.
using(var tw = new StreamWriter(path, false))
{
tw.WriteLine(textBox2.Text);
}

Save file to a specific folder in Windows Form C#

I am trying to save some selected file in a folder(images) inside my application
I am able to get the file using following code:
private void button1_Click(object sender, EventArgs e)
{
string imagelocation = "";
OpenFileDialog dialog = new OpenFileDialog();
if(dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{
textBox2.Text = dialog.FileName;
}
}
For saving the file I got in textBox2, I tried following code. But with following code I have to also select the path where I want to save the file.
What If I want to (set my path permanently to 'images' folder as shown in pic) for saving?
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog f = new SaveFileDialog();
if(f.ShowDialog() == DialogResult.OK)
{
using(Stream s = File.Open(f.FileName, FileMode.CreateNew))
using(StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox2.Text);
}
}
}
2 Approaches to Solve this problem
First Approach: (Browser the File and click Save, to automatically save the selected file to Image Directory)
private void button2_Click(object sender, System.EventArgs e)
{
var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
var imageDir = Path.Combine(assemblyParentPath, "Image");
if (!Directory.Exists(imageDir))
Directory.CreateDirectory(imageDir);
using (Stream s = File.Open(imageDir+"\\"+Path.GetFileName(textBox1.Text), FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
Second Approach: (Browser the File and Save Opens SaveDialog with Directory as Image Directory and File name as Previously selected File)
private void button2_Click(object sender, System.EventArgs e)
{
var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
var imageDir = Path.Combine(assemblyParentPath, "Image");
if (!Directory.Exists(imageDir))
Directory.CreateDirectory(imageDir);
SaveFileDialog f = new SaveFileDialog();
f.InitialDirectory = imageDir;
f.FileName = textBox1.Text;
if (f.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(imageDir + "\\" + Path.GetFileName(textBox1.Text), FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
}```
Does this code work for you?
private void button1_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Title = "Select Picture";
dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
dlg.Filter = "Common Picture Files|*.gif;*.png;*.bmp;|All Files|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.FileName;
}
}

Writing to file, directory error

public partial class Form1 : Form
{
string path = $#"C:\Journal";
string fileName = #"";
string compact = "";
public Form1()
{
InitializeComponent();
fileName = monthCalendar1.SelectionRange.Start.ToShortDateString() + ".txt";
compact = (path + #"\" + fileName);
}
private void btnWrite_Click(object sender, EventArgs e)
{
if(File.Exists(fileName))
{
StreamWriter myWriter = new StreamWriter(compact, true);
myWriter.WriteLine(txtDisplay.Text);
myWriter.Close();
}
else
{
StreamWriter myWriter = new StreamWriter(compact, true);
myWriter.WriteLine(txtDisplay.Text);
myWriter.Close();
}
}
I'm trying to write stuff from a multiline textbox into a file using the Monthly calender date as the file name. I keep getting an error that the directory does not exist. Not sure of the reason since i created the folder in the path, I appreciate the help.
System.IO.DirectoryNotFoundException was unhandled
It seems, you have to create directory. Another issue is
fileName = monthCalendar1.SelectionRange.Start.ToShortDateString() + ".txt";
since Short DateTime Format can contain '/' or '\' which are forbidden within file names.
public Form1() {
InitializeComponent();
// ToString(...) we don't want / or \ in the file's name
fileName = monthCalendar1.SelectionRange.Start.ToString("dd'.'MM'.'yyyy") + ".txt";
compact = Path.Combine(path, fileName);
}
private void btnWrite_Click(object sender, EventArgs e) {
Directory.CreateDirectory(Path.GetDirectoryName(compact));
// Or File.AppendAllText(compact, txtDisplay.Text);
File.AppendAllLines(compact, new string[] {txtDisplay.Text});
}

Find a file in my directory

I need to get the path of a file which is in a specific directory.The user selects a csv file from a OpenFileDialog. If the csv file has field that ends at .txt then take the path of that file and put it in a pathfile variable. The new file has to be placed, by the user, in the same directory as the csv file.
EDIT: How do I put the path of the file in a variable ?
EDIT2: The file could be placed everywhere, for example: C://george.csv. So I want to take a txt from the directory c:// .Or if the file is here: C://Documents/anna.csv. The text has to be C://Documents/textfile.txt.
EDIT3: The csv file that the user has opened is at c://Documents/gonow.csv
The file gonow.csv is : one, two, tree, four, textfile.txt, five, six, seven.
When a field has extension .txt then the program has to go and cath the path. In this case the path is c://Documents/textfile.txt.
private void button3_Click(object sender, EventArgs e)
{
string filename = "";
DialogResult result = openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog2.FileName;
textBox3.Text = filename;
System.IO.StreamReader file2 = new System.IO.StreamReader(textBox3.Text);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (Path.GetExtension(colB[j]) == ".csv")
textBox2.Text += " comma separated, in line " + j + "" + Environment.NewLine;
}
Try
string path = Path.GetDirectoryName(filename);
EDITED according to your EDIT3:
Use this function to open your csv file and get new complete filename.
private string GetFilename(string csvFilename)
{
string path = Path.GetDirectoryName(csvFilename);
string[] lines = File.ReadAllLines(csvFilename);
foreach (string line in lines)
{
string[] items = line.Split(',');
string txt = items.First(item => item.ToLower().Trim().EndsWith(".txt"));
if (!String.IsNullOrEmpty(txt))
return Path.Combine(path, txt);
}
return "";
}
iF you need to put the txt file (the generated file) in the same folder as that of the CSV file, you can store the path of the CSV file and create the txt file in theat folder.
To do this you may like to have a variable like this:
private void button3_Click(object sender, EventArgs e)
{
string filename = "";
string FolderPath;
DialogResult result = openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog2.FileName;
FolderPath = Path.GetDirectoryName(filename);
textBox3.Text = filename;
System.IO.StreamReader file2 = new System.IO.StreamReader(textBox3.Text);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (Path.GetExtension(colB[j]) == ".csv")
textBox2.Text += " comma separated, in line " + j + "" + Environment.NewLine;
}
The FolderPAth variable holds the path to the folder. You can create the txt file in this folder. This means that the txt file is in the same folder as of the csv file. If you need to access this in a different method, you may declare it in relevant scope.

Categories