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.
Related
I am trying to write a C# program that will allow me to select a file and copy that file to a list of directories.
I've written the code to copy the file over and it works, the problem I am having to getting it to copy the file to each line of the textbox, as each line is a different directory.
This is what I have so far:
private void button3_Click(object sender, EventArgs e)
{
int line = 1;
string FileToCopy = listBox3.GetItemText(listBox3.SelectedItem);
if (File.Exists(FileToCopy + #"\user.ini"))
{
File.Copy(FileToCopy + #"\user.ini", textBox1.Lines[line - 1] + #"\user.ini", true);
line++;
label5.Text = "Environment Updated";
}
else
{
label5.Text = "File of Path not Found";
}
}
I'm pretty sure there is a simple solution to this but my searches haven't brought up anything yet. I'm still quite new to C# and programming in general, any help would be appreciated.
Assuming textbox has text
Path1
Path2
Path3
.....
PathN
Then split the text into lines
var lines = textBox1.Text.Split(new string[]{Environment.NewLine}, System.StringSplitOptions.RemoveEmptyEntries);
And then for each line copy the file over.
foreach(var path in lines) {
File.Copy(FileToCopy + #"\user.ini", path + #"\user.ini", true);
}
Hy everyone,
I would like to copy multiple selected files with openfiledialog to a folder which is defined as #"C:\TestFolder\"+ textBox1.Text. My problem is that somehow the program writes the textBox content in the file name too.
Please find below my code:
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog od = new OpenFileDialog();
od.Filter = "All files (*.*)|*.*";
od.Multiselect = true;
if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string targetPath = #"C:\TestFolder\"+ textBox1.Text;
string path = System.IO.Path.Combine(targetPath, textBox1.Text);
if (!System.IO.Directory.Exists(targetPath)
{
System.IO.Directory.CreateDirectory(targetPath);
}
foreach (string fileName in od.FileNames)
{
System.IO.File.Copy(fileName, path + System.IO.Path.GetFileName(fileName));
}
}
}
Any input would be appreciated!
Try this one:
string Main_dir = #"C:\TestFolder\";
string Sub_dir = textBox1.Text + #"\";
string targetPath = System.IO.Path.Combine(Main_dir, Sub_dir);
{
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
foreach (string fileName in od.FileNames)
System.IO.File.Copy(fileName, targetPath + System.IO.Path.GetFileName(fileName), true);
}
Backslash is missing
#"\"
These things are equivalent.
string targetPath = #"C:\TestFolder\"+ textBox1.Text;
string path = System.IO.Path.Combine(targetPath, textBox1.Text);
I would drop the first one for the Path.Combine call as it is portable and robust when it comes to the separators.
Currently, I have a browser dialog that opens and allows the user to select a folder in which doc / docx files will be merged into one file. At the moment, it is rigged up to merge files once the 'DialogResult.ok' button is dismissed in the browser dialog. as shown below:
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 = #"C:\";
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;
}
private void combineButton_Click(object sender, EventArgs e)
{
string[] AllDocFolder = Directory.GetFiles(selectedFolder, "*.doc");
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(AllDocFolder, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + AllDocFolder.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
the issue i am having is that i want the 'combineButton' to merge the documents as opposed to the 'DialogResult.ok'. When i copy the lines:
string[] AllDocFolder = Directory.GetFiles(selectedFolder, "*.doc");
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(AllDocFolder, outputFileName, true);
into the combineButton area, i get an error saying 'the name 'selectedFolder' does not exist in the current context'. This may be a stupid question, but is there a quick way to remedy this?
As far as I understand your problem, you want to split the folder selection and the merging of the documents, right?
So you could put the information about the target directory into a class variable:
public class MyForm
{
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 = #"C:\";
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");
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (_sourceFiles != null && _sourceFiles.Length > 0)
{
string outputFileName = (#"C:\Test\Merge\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);
}
}
}
I opened a directory and I read some files in that directory amd made some changes, now I want to save the changes with the same file names at F:\BI\Out\ and keep the original files.
when I added these two lines
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
I was able to save the files under the new folder\Out,
but when I opened them I found that only one file is changed correctly and all the other files the old words are replace by blank space not by the new words.
Can anyone help me Thanks
string text = "";
string[] files;
private void Form1_Load(object sender, EventArgs e)
{
try
{
files = Directory.GetFiles(#"F:\BI\In\", "*.*", SearchOption.AllDirectories);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
this.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtEtlPath.Text == "")
{
MessageBox.Show("Please Enter path");
txtEtlPath.Focus();
}
else
{
foreach (string file in files)
{
if (System.IO.File.Exists(file))
{
text = File.ReadAllText(file);
text = text.Replace("Company_Address", txtCompanyAddress.Text + "_BI");
text = text.Replace("Company_Name", txtCompanyName.Text.Trim() + "_BIDW");
text = text.Replace("C:\\BIfolder",cboDrive.Text + txtEtlPath.Text.Trim());
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
}
Within your foreach () loop:
If you want the subfolder structure of the files found, do a replace on the filepath:
var outFilePath = file.Replace(#"F:\BI\In\", #"F:\BI\Out\");
You will need to create the subfolder before you can write the changed file:
new FileInfo(outFilePath)).Directory.Create();
If you don't want the subfolders, you can write directly into the top folder:
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
Writing is simple, just keep in mind there is an optional encoding parameter:
File.WriteAllText(outFilePath, text);
In debug mode, while running the C# WinFOrms App, After I select the files through the OpenFileDialog, I get the
Error: Could not read file from disk.
Original error: Index was outside the bounds of the array.
Do you have any idea on how to fix this Error?
Here's my code:
// When the user clicks on Select Files Button, this happens
private void sourceFiles_Click(object sender, EventArgs e)
{
Stream myStream;
int i = 0;
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 (this.sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
string tempFolder = System.IO.Path.GetTempPath();
foreach (string FileName in this.sourceFileOpenFileDialog.FileNames)
{
this.sourceFileOpenFileDialog.FileNames[i] = FileName;
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);
i++;
System.IO.File.Copy(FileName, tempFolder + #"\" + FileName);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
//method for the sourcefileOpenFileDialog. Do I need anything here?
private void sourceFileOpenFileDialog_FileOk(object sender, CancelEventArgs e)
{
}
//method for the listbox. Do I need anything here?
private void listBoxSourceFiles_SelectedIndexChanged(object sender, EventArgs e)
{
}
Thanks!
What you are doing doesn't seem to make a lot of sense. What is the following line supposed to do?
this.sourceFileOpenFileDialog.FileNames[i] = FileName;
Just change your foreach to this:
foreach (string FileName in this.sourceFileOpenFileDialog.FileNames)
{
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + FileName);
System.IO.File.Copy(FileName, Path.Combine(tempFolder, Path.GetFileName(FileName)));
}
The error arises from the fact, that you have two variables named sourceFileOpenFileDialog. One is a member of your class and one is declared inside the method.
The one that is declared inside the method is only ever used in the following line:
Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);
Because this instance is not used to show the dialog to the user, its FileNames property has a Length of 0 and therefore trying to access any items in it results in the exception.
Update:
There is one more problem:
FileName is a complete path, so appending it to the temp path will result in an invalid path. Also, consider using Path.Combine to combine two paths:
Path.Combine(tempFolder, Path.GetFileName(FileName))