Hello i'm trying to write a program that takes 3 user inputs: file path, username, and computer name and then create a batch file for each computer name in the list. I have not written the create batch file part yet but I am having trouble taking the multiple computers from the computer text box and creating separate lines of code out of them.
So if there are 3 computer names inside the computer textbox, id like to when the user hits the button, output each computer name on a different line.
if the computer name textbox contained the following computer names: M22-LIBRL74258S, M22-LIBRL74257S, and M22-LIBRL74256S
the output would be :
XCOPY "C:\Documents and Settings\Administrator\Desktop\file.exe" "\M22-LIBRL74258S\c$\Users\username\desktop"
XCOPY "C:\Documents and Settings\Administrator\Desktop\file.exe" "\M22-LIBRL74257S\c$\Users\username\desktop"
XCOPY "C:\Documents and Settings\Administrator\Desktop\file.exe" "\M22-LIBRL74256S\c$\Users\username\desktop"
Thanks!
WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void browsebtn_Click(object sender, EventArgs e)
{
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Title = "Select a File to Send";
// Show the Dialog.
// If the user clicked OK in the dialog and
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
string strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
pathtxt.Text = strfilename.ToString();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void createbtn_Click(object sender, EventArgs e)
{
string filepath = pathtxt.Text.ToString();
string username = usertxtbox.Text.ToString();
string computer = computerstxtbox.Text;
string[] split = computer.Split(new char[] { '\n' });
foreach (string l in split)
{
var strIP = "XCOPY \"" + pathtxt.Text + '"' + ' ' + '"' + "\\" + "\\" + l + "\\" + "c$" + "\\" + "Users" + "\\" + username + "\\" + "desktop" + '"';
//This is to see it
MessageBox.Show(strIP);
}
Try and replace the line
string[] split = computer.Split(new char[] { '\n' });
with this instead
string[] split = computer.Split(new String[] {"\r\n"}, StringSplitOptions.None);
Also if your computer names are seperated by commas, you must also specify them in the split. e.g. new String[] {"\r\n", ","}
Related
I have an input path that contains an unknown number of
subdirectories.
I want to use 7zip to zip each of them and the zip file will be in the selected output path.
Below is the concept of this program.
Below is the 7zip code I try to achieve the result, but no idea how to do.
string source = textBoxInput.Text + "\\*";
string target = Path.Combine(tBoxOutput.Text, source + DateTime.Now.ToString());
foreach (var folder in Directory.GetDirectories(source))
{
_sevenZip.CreateZipFile(folder, target);
}
Below is the 7z in command line I use to this program.
try
{
ProcessStartInfo zipProcess = new ProcessStartInfo();
zipProcess.FileName = #"E:\Program Files\7-Zip\7z.exe";
zipProcess.Arguments = "a -t7z \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
zipProcess.WindowStyle = ProcessWindowStyle.Minimized;
Process zip = Process.Start(zipProcess);
zip.WaitForExit();
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
I remember helping you once with that question , i guess my answer was not to your satisfaction,
I've tried better this time:
this is the window:
these are the folders I used, just like in your example:
'choose source' and 'choose target' button opens a folder dialog
you were in the right direction, a for loop that runs over the subdirectories. i guess the hard part was getting the correct names. you just need to make sure that the target name would have a ".7z" extension.
and the code is fairly simple:
string zipProgramPath = #"C:\Program Files\7-Zip\7z.exe";
public Form1()
{
InitializeComponent();
}
public void CreateZipFile(string sourceName, string targetName)
{
try
{
ProcessStartInfo zipProcess = new ProcessStartInfo();
zipProcess.FileName = zipProgramPath; // select the 7zip program to start
zipProcess.Arguments = "a -t7z \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
zipProcess.WindowStyle = ProcessWindowStyle.Minimized;
zipProcess.UseShellExecute = true;
Process zip = Process.Start(zipProcess);
zip.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void btnBrowseSource_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
lblSource.Text = fbd.SelectedPath; //label next to the button
}
}
}
private void btnBrowseTarget_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
lblTarget.Text = fbd.SelectedPath.ToString(); //label next to the button
}
}
}
private void btnExecute_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(lblSource.Text) || string.IsNullOrEmpty(lblTarget.Text))
{
MessageBox.Show("Choose input directory and output directory");
}
else
{
foreach (var folder in Directory.GetDirectories(lblSource.Text))
{
string folderName= Path.GetFileName(folder);
string targetName = Path.Combine(lblTarget.Text, folderName+ ".7z" );
CreateZipFile(folder, targetName);
}
}
}
so after choosing the right directories, and pressing execute
the result is as required :
Here is the PowerShell script will do the same. SourceFolders will have your test, test1, test2 folders. Compressed files will gets stored into C:\DestinationFolder. You just have run this script from PowerShell command prompt.
Import-Module Microsoft.PowerShell.Management
$sourcefolders = Get-ChildItem "C:\SourceFolders"
$outputfolder = "C:\DestinationFolder"
for ($i=0; $i -lt $sourcefolders.Count; $i++) {
$folderPathToCompress = $sourcefolders[$i].FullName
$compressFileName = $sourcefolders[$i].Name
"Compressing folder ="+$folderPathToCompress;
.\7z a -t7z $outputfolder\$compressFileName".7z" $folderPathToCompress
}
I created a button that will allow a user to create a CSV based on a directory comparison. I compiled the code, and everything looks ok. I go to run the program, however, and I get a "Access is denied" error.
private void button1_Click_1(object sender, EventArgs e)
{
string csv = string.Empty;
FolderBrowserDialog fbd = new FolderBrowserDialog();
using (var sfd = new SaveFileDialog())
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string folderPath = fbd.SelectedPath;
string filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(folderPath + "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv", csv);
}
Is there another way to save the datagridview into a CSV with the file extension give in the filename string?
Do you have permission to write on the folder?
Try use File.WriteAllLines:
File.WriteAllLines(folderPath + "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv", csv);
This program is ran from the context menu after right clicking on a pdf file, it simply adds "\ CALL OFF" to the selected file, locally the program works fine, even with spaces. When ran on a file on my nas in which the path contains spaces the output from GetCommandLineArgs stops at the first space.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] args = System.Environment.GetCommandLineArgs();
textBox1.Text = args[1];
}
private void button2_Click(object sender, EventArgs e)
{
ProcessStartInfo start = new ProcessStartInfo();
start.Arguments = "-add-text \"/ CALL OFF\" -font \"Helvetica-Bold\" -font-size 14 -pos-left \"194 776\" " + textBox1.Text + " -o out.pdf";
start.FileName = "cpdf";
Process.Start(start);
}
}
String Join all the command line arguments back together, using space as separator, into one string and use that as the argument. You'll also need to add double-quotes around the textBox1.Text when used in start.Arguments to ensure it is received as one:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] args = System.Environment.GetCommandLineArgs().Skip(1).ToArray();
textBox1.Text = String.Join(" ", args);
}
private void button2_Click(object sender, EventArgs e)
{
ProcessStartInfo start = new ProcessStartInfo();
start.Arguments = "-add-text \"/ CALL OFF\" -font \"Helvetica-Bold\" -font-size 14 -pos-left \"194 776\" "
+ "\"" + textBox1.Text + "\"" + " -o out.pdf";
start.FileName = "cpdf";
Process.Start(start);
}
}
You need to enclose the path name in quotes, you add \":
string quoted = "\"" + textBox1.Text + "\"";
to get:
start.Arguments = "-add-text \"/ CALL OFF\" -font \"Helvetica-Bold\" -font-size 14 -pos-left \"194 776\" \"" + textBox1.Text + "\" -o out.pdf";
If you are passing it as a command line argument to the program then you need to quote it there as well:
myExe -file "Long path with spaces\file.pdf"
I'm new to C#, I want to create a file with extension .txt and file name as with first three characters of textbox value.I am creating the file but i dont now how to store the file in the required destination for example c:\ Documents\ION.please help me.
Thank You For reading this...
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Create_File";
string fileName = textBox1.Text.Substring(0, 3) + ".txt";
File.Create(fileName);
MessageBox.Show("ok");
}
Thank U guys ,with all Your help I solved it
private void button2_Click(object sender, EventArgs e)
{
button2.Text = "SAVE";
var files = Directory.GetFiles(#"C:\\Users\\Apple\\Desktop\\proj").Length;
string fileName = textBox1.Text.Substring(0, 3) + -+ ++files + ".txt";
string path2 = Path.GetFullPath("C:\\Users\\Apple\\Desktop\\proj");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string var = Path.Combine(docPath, path2);
string var1 = Path.Combine(var, fileName);
using (StreamWriter writer = new StreamWriter(var1))
{
string var6 = textBox1.Text;
string var7 = " ";
string var8 = textBox2.Text;
string var9 = string.Concat(var6, var7, var8);
writer.WriteLine(var9);
}
MessageBox.Show("File created");
}
string fileName = textBox.Text.Substring(0,3) + ".txt";
using(StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine("Hello world!");
}
Note that it would be wise to confirm that the TextBox contains at least three characters before doing that.
This is the same issue i had and got it solved by doing it this way :
File.WriteAllText(folderPath + "DataExport_"+srchCat_txtbox.Text+"_"+DateTime.Now.ToString("ddMMyyyy")+".csv", csv);
I needed to save CSV files with a unique name which includes a global name "DataExport", a category name "srchCat_txtbox.Text" value and the current date.
I can't seem to get access to the file I'm working with in the program I'm writing. I'm not sure how exactly to work this since I want my program to open a file of your choice, which it does, then I want it to be able to take in info into an arrary, which it does, then from there, write that information from the array to the file you opened up. When I try some code to start working on it it tells me, "The process cannot access the file 'file' because it is being used by another process." Here is what I have so far. Please let me know. Thank you. The problematic areas is the Save_Click section of the code where I wrote "This is a test" Thanks.
public partial class ListingSearch : Form
{
string line;
DialogResult result;
string fileName;
int i = 0;
string[] first = new string[100];
string[] last = new string [100];
string[] phone = new string [100];
string[] grade = new string [100];
public ListingSearch()
{
InitializeComponent();
MessageBox.Show("Please be sure to open a file before beginning");
}
private void OpenFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog filechooser = new OpenFileDialog())
{
result = filechooser.ShowDialog();
fileName = filechooser.FileName;
System.IO.StreamReader file =
new System.IO.StreamReader(fileName);
while ((line = file.ReadLine()) != null)
{
string[] words = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
//firstName.Text = words[4];
//lastName.Text = words[5];
//telephone.Text = words[6];
//GPA.Text = words[7];
}
Read.Enabled = true;
}
}
private void Save_Click(object sender, EventArgs e)
{
File.AppendAllText(fileName, "This is a test");
}
private void Read_Click(object sender, EventArgs e)
{
MessageBox.Show(fileName);
MessageBox.Show(File.ReadAllText(fileName));
}
private void info_Click(object sender, EventArgs e)
{
first[i] = firstName.Text;
firstName.Text = " ";
last[i] = lastName.Text;
lastName.Text = " ";
phone[i] = telephone.Text;
telephone.Text = " ";
grade[i] = GPA.Text;
GPA.Text = " ";
i++;
}
private void displayinfo_Click(object sender, EventArgs e)
{
if (i == 0)
MessageBox.Show("Nothing to display!");
else
for (int j = 0; j < i; j++)
{
MessageBox.Show(first[j] + " " + last[j] + "\r" + phone[j] + "\r" + grade[j]);
}
}
You get error here
File.ReadAllText(fileName)
because you open same file before it here
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
You need to close the file after you are finished reading it. Also, not sure why you are opening the file at all, since you subsequently use File.ReadAllText which will handle opening and closing the file all on its own.
Seems like your OpenFile_click event should just look like this:
using (OpenFileDialog filechooser = new OpenFileDialog())
{
result = filechooser.ShowDialog();
fileName = filechooser.FileName;
string[] words = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
Read.Enabled = true;
}
You haven't closed your StreamReader. C# will lock the file until you do. Or you could use a StreamWriter after you closed your StreamReader