My C# console program copies 2 folders into 1. It works but I am new to C#. I cant figure out how I make the program skip the alert window "are you sure you want to overwrite the files".
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic.FileIO;
using System.Diagnostics;
namespace MirrorSystem {
class Program {
static void Main(string[] args)
{
string source1 = #"folder1";
string source2 = #"folder2";
string destination = #"destination";
try
{
Console.WriteLine("Starting..");
FileSystem.CopyDirectory(source1, destination, UIOption.AllDialogs);
FileSystem.CopyDirectory(source2, destination, UIOption.AllDialogs);
Console.WriteLine("Success!");
System.Threading.Thread.Sleep(5000);
Environment.Exit(0);
Console.ReadKey();
}
catch (OperationCanceledException)
{
Console.WriteLine("Canceled!");
Console.ReadKey();
}
}
}
}
You can pass the value true as the third (overwrite) parameter. Here is the official documentation for the method:
public static void CopyDirectory(
string sourceDirectoryName,
string destinationDirectoryName,
bool overwrite
)
The description of the overwrite parameter:
overwrite
Type: System.Boolean
True to overwrite existing files;
otherwise False. Default is False.
Source.
You can use method File.Copy --> https://msdn.microsoft.com/es-es/library/9706cfs5(v=vs.110).aspx
The third parameter allows you to specify whether you should or should not overwrite existing files with the same name in the destination folder.
Related
I am trying to create script for my terminal server, which will move all folders with their contents, created in the wrong place. I don't know which names these folders will have. As I noticed, moving folders in C# is a problem for some reason. Can someone help me with my code? It just deleting my test folders and nothing moves.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.VisualBasic.FileIO;
namespace ConsoleApp1
{
public class Programm
{
public static void Main()
{
string root = #"C:\Users\user1\Desktop";
string[] subdirectoryEntries = Directory.GetDirectories(root);
string destDirname = #"D:\confiscated";
foreach (string path in subdirectoryEntries)
{
FileSystem.MoveDirectory(path, destDirname, true);
}
}
}
}
This is how to do it:
string startPath = #"YOURSTARTPATH";
string endPath = #"YOURENDPATH";
foreach (string directory in Directory.GetDirectories(startPath))
{
Directory.Move(directory, Path.Combine(endPath, Path.GetFileName(directory)));
}
This way, you will use the already provided by the framework classes to work with directories.
No need to include Microsoft.VisualBasic.FileIO
I have the following class which writes new line to a text file.
using System;
using System.Text;
using System.IO;
namespace TextStreamer
{
class TextWriter
{
private string _FilePath;
private string _TextToAdd;
// Constructor will assign file Path variable and check if file is valid
public TextWriter(string filePath)
{
this._FilePath = filePath;
ValidateFile();
}
// Validate if the text file exist
private void ValidateFile()
{
// If file does not exist show error message
// and create new text file
if(!File.Exists(_FilePath))
{
Console.WriteLine("File not found");
File.Create(_FilePath);
Console.WriteLine("Created new file {0}", _FilePath);
}
}
// Write new line to the text file
public void WriteNewLine(string text)
{
this._TextToAdd = text + Environment.NewLine;
File.AppendAllText(_FilePath, _TextToAdd);
}
}
}
Right now if the file does not exist it will write a message to the console and then it will create the text file, but what if i used say WPF application, in this case i prefer showing a message box with the same message, how can i achieve that.
I tried throwing exception FileNotFoundException but that just crashes the program and exit.
A simple way to achieve this is by using a public variable to change the option to console log or show message.
Add the namespace for the generic message box:
using System.Windows;
And add a public variable in your class that will let you programmatically change the logging method, such as:
public bool UseMsgBox = false;
You could improve this by using things like using an int or enum to have more logging methods, though a bool is fine for only 2 options.
Add a logging method such as:
private void LogMsg(string msg)
{
if(UseNsgBox) MessageBox.Show(msg);
else Console.WriteLine(msg);
}
And replace your Console.WriteLine's with LogMsg instead.
Make sure to change the option when you create your class:
TextWriter textWriter = new TextWriter("SomeFile.txt");
textWriter.UseMsgBox = true; // or false
Actually, this might not work as you instantly call the LogMsg when your class is created, so perhaps add it as an initialization parameter as well:
public TextWriter(string filePath, bool useMsgBox = false)
{
UseMsgBox = useMsgBox;
// ...
}
I am trying to figure out if any of the below 3 locations are accessible and append to build location,if multiple locations are accessible pick one of them and bail out if none exit,can anyone provide info on how to do this?
1.BIN-LOC-WiFi-FW\loc_proc\bin
2.loc_proc\pkg\cnss_proc\bin
3.loc_proc_ps\package
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aputloader
{
class Program
{
static void Main(string[] args)
{
string buildlocation = #"\\location\builds784\INTEGRATION\LOC.1.2-00028-Z-1";
//check if atleast one of the following folders exist and append to buildlocation
//1.BIN-LOC-WiFi-FW\loc_proc\bin
//2.loc_proc\pkg\cnss_proc\bin
//3.loc_proc_ps\package
//multiple folders exist ,pick one
//none exist ,bail out
}
}
}
Maybe something like this?
if(Directory.Exists("BIN-LOC-WiFi-FW\loc_proc\bin"))
{
// This path is a directory
}
else if(Directory.Exists("loc_proc\pkg\cnss_proc\bin"))
{
// This path is a directory
}
else if(Directory.Exists("loc_proc_ps\package")
{
// This path is a directory
}
else
{
Console.WriteLine("No valid folder exists.");
// Do nothing.
}
I created this class "XML_Toolbox" that could be used by any of my forms to perform any of the key XML actions that i am going to be using repeatedly. So with that being said, here is that class' code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
namespace Personal_Finance_Manager
{
class XML_toolbox
{
public static void createFile (string filename, string filePath)
{
string createPath = filePath + #"\" + filename + ".txt";
if (file.exists(createPath))
{
StreamWriter outfile = new StreamWriter(createPath, true);
}
else
{
MessageBox.Show("This file already exists!!! Please choose another name!");
}
}
}
}
all the individual parts were working when called from another form up until i added the:
if (file.exists(createPath)) {}
IF statement.
Now i am getting the
The name "file" does not exist in the current context
error. I have the
using System.IO;
what else am i missing?
Thanks!
Class name is File not file, method name is Exists. C# is case-sensitive.
It's called File, not file.
File.Exists()
I'm working on a Windows application where I need to use clipboard data. I am trying to copy text from clipboard by the code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace MultiValuedClipBoard
{
class Class1
{
public String SwapClipboardHtmlText(String replacementHtmlText)
{
String returnHtmlText = "hello";
if (Clipboard.ContainsText(TextDataFormat.Html))
{
returnHtmlText = Clipboard.GetText(TextDataFormat.Html);
Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
}
return returnHtmlText;
}
}
}
Calling the above function by:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Media;
namespace MultiValuedClipBoard
{
class Program
{
static void Main(string[] args)
{
Class1 aas = new Class1();
string a = aas.SwapClipboardHtmlText("chetan");
Console.WriteLine(a);
Console.ReadLine();
}
}
}
When running this code it gives the output "Hello" which is the default value, not clipboard data.
Your code will not work because of two reasons:
[1] When you say:
if (Clipboard.ContainsText(TextDataFormat.Html))
Here you are basically assuming that the clipboard already contains a text and that too in HTML format, but depending on the values you are setting in the clipboard it doesn't look like you are intending to use the pre-existing clipboard value anywhere in your program. So, this if condition should not be there.
[2] Secondly, you are further trying to set the string "chetan" to the clipboard which is definitely not in HTML format. So,
Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
becomes
Clipboard.SetText(replacementHtmlText, TextDataFormat.Text);
Hence, effectively, your new code becomes something like this:
String returnHtmlText = "hello";
//if (Clipboard.ContainsText(TextDataFormat.Html))
//{
returnHtmlText = Clipboard.GetText(TextDataFormat.Text);
Clipboard.SetText(replacementHtmlText, TextDataFormat.Text);
//}
return returnHtmlText;
Clearly Clipboard.ContainsText(TextDataFormat.Html) evaluates to false. Which means that the clipboard in fact does not contain text in the format you specify.
I changed your program to prove the point:
[STAThread]
static void Main(string[] args)
{
Clipboard.SetText("boo yah!", TextDataFormat.Html);
Class1 aas = new Class1();
string a = aas.SwapClipboardHtmlText("chetan");
Console.WriteLine(a);
Console.WriteLine(Clipboard.GetText(TextDataFormat.Html));
Console.ReadLine();
}
Output:
boo yah!
chetan