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);
}
Related
I have two little question which I am struggling with. Both dealing with lines really.
1: How I can I place the following Regex code into a Split()?
Regex(#"\r\n|\n|\r", RegexOptions.Singleline)
int num = copyText.Split().Length - 1;
//copyText is a string
2: When I write to a text file from a rich text box, all the text in the text file is displayed on one line. How can I get the text to be displayed as it looks in the rich text box?
private void Write(string file, string text) {
//Check to see if _Parsed File exists
if (File.Exists(file)) {
//Write to _Parsed text file
using(StreamWriter objWriter = new StreamWriter(file)) {
objWriter.Write(text);
objWriter.Close();
}
} else {
MessageBox.Show("No file named " + file);
}
}
private void btnReplace_Click(object sender, EventArgs e) {
// Replace -ing ending words to XXXXXX code goes here...
//Write into richTextBox2
wholeText = richTextBox1.Text + oldSummary + copyText + newSummary;
Write(Second_File, wholeText);
richTextBox2.Text = wholeText;
}
For the 1st problem try this:
int num = Regex.Split(copyText, #"\r\n|\n|\r").Count - 1;
See: MSDN
For the 2nd one try:
File.WriteAllLines(FileName, richTextBox.Lines);
And please read possible dublicate: From RichTextBox to text files, line after line
RichTextBox.SaveFile(string path, RichTextBoxStreamType); built-in function
1: I suggest:
int num = copyText.Split(new string[] { Environment.NewLine },
StringSplitOptions.None).Count();
2: Make sure richtextbox1.MultiLine is set to true
1st option
I'd rewrite the Write method like this:
private void Write(string file, RichTextBox box)
{
if (File.Exists(file))
{
System.IO.File.WriteAllLines(file, box.Lines);
}
else
{
MessageBox.Show("No file named " + file);
}
}
2nd option
private void Write(string file, RichTextBox box)
{
if (File.Exists(file))
{
StreamWriter sw = File.CreateText(file);
for (int i = 0; i < box.Lines.Length; i++)
{
sw.WriteLine(box.Lines[i]);
}
sw.Flush();
sw.Close();
}
else
{
MessageBox.Show("No file named " + file);
}
}
You could also try foreach if you want.
The 2nd option is more complicated but better.
And pass the RichTextBox as variable to the Write method like this:
Write(#"C:\path\to\file.ext", RichTextBox boxToWrite);
Hi all firstly sorry for my English but i hope you can understand me..
Im doing a project on VS2008-Smart Device Project-WinCE 5.0 Project.
I need to create text file to DATA folder which is under the main directory of program.
There is my code, there is no error messege but its not creating text file.My directory always returns null.
Whats wrong with that code?
if (Form2.dosya_adi != null)
{
string cfile = Form2.chosenfile;
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\DATA\\" + cfile+ ".txt";
}
else
{
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\DATA";
}
try
{
StreamReader Read_File= File.OpenText(path);//Dosyayı açmaya çalış olmaz ise catch bloğuna geç
ReadFile.Close();
}
catch
{
StreamWriter Write_File= File.CreateText(path+ i.ToString()+".txt");// yeni dosya oluştur.
Write_File.Close();
}`
And heres the form2 which includes listbox and listbox shows directory for if there is a file or not..
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
path = path + "\\DATA";
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] rgFiles = di.GetFiles();
foreach (FileInfo fi in rgFiles)
{
listBox1.Items.Add(fi.Name);
}
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
chosen_file = listBox1.GetItemText(listBox1.SelectedItem);
Form1 form1 = new Form1();
form1.Show();
this.Hide();
}
else
{
MessageBox.Show("HATA:Hiçbir Değer Seçilmedi!"); // That means error:no value chosen!
}
}
Your code does not prepare the path variable properly. In one case it contains a file name, in another case it contains only a path name:
if (Form2.dosya_adi != null)
{
string cfile = Form2.chosenfile;
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\DATA\\" + cfile+ ".txt";
}
else
{
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\DATA";
}
Then you try to open a file - even though the variable does not contain a file name in the first place. If that leads to an exception, you try to create a file, but actually, you're not adding a path separator to the path. So I think your catch block should read:
StreamWriter Write_File= File.CreateText(path + "\\" + i.ToString() + ".txt");// yeni dosya oluştur.
Write_File.Close();
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);
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.
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))