the condition that changes the directory - c#

goal: we are not talking about files, but about folders. if the desired folder, which is specified in the array of strings, is available on the desktop, then we need to get subdirectories and paths to this folder, if the desired folder is not on the desktop, then the search for this folder has already been performed in appdata, and then the same thing, if the folder is present, then we get subdirectories and paths to this folder.
string[] directory = new string [] {#"folder1/", #"folder3/", }
foreach (string sPath in directory)
{
string Path;
if (sPath.Contains("folder1"))
{
Path = Desktop + sPath;
}
else
{
Path = Appdata + sPath;
}
there is an if (sPath.Contains("folder1"))
I intended the string Path to first take the Path = "Desktop + sPath" logic to return the names of the subdirectories of the folder1 folder
if (Directory.Exists(Path)) foreach (string folder in Directory.GetDirectories(Path))
{
Console.WriteLine(folder);
this code does not work for me = (if you delete a folder from the desktop, which, for example, was present, then the search from another place that is specified in the code is not carried out( how to fix the situation?
string Path;
if (sPath.Contains("folder1"))
{
Path = Desktop + sPath;
}
else
{
Path = Appdata + sPath;
}
full code
string [] directory = new string [] {#"folder1/", #"folder3/", }
foreach (string sPath in directory)
{
string sFullPath;
if (sPath.Contains("folder1"))
{
sFullPath = Desktop + sPath;
}
else
{
sFullPath = Appdata + sPath;
}
if (Directory.Exists(sFullPath)) foreach (string folder in Directory.GetDirectories(sFullPath))
{
Console.WriteLine(folder);
}
}

First of all we should come to terms. To be "available on the desktop" is to be a subfolder of
// Have a look at
// Environment.SpecialFolder.CommonDesktopDirectory
// Environment.SpecialFolder.DesktopDirectory
// as well
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
then we can manipulate with directory array:
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string[] directory = new string [] {#"folder1/", #"folder3/", };
foreach (string sPath in directory) {
if (Directory.Exists(Path.Combine(desktop, sPath))) {
// available on the desktop
}
else if (Directory.Exists(Path.Combine(appData, sPath))) {
// available on the AppData
}
else {
// not exists
}
}

Related

How can I run an exe file with c# (I can't use Process.Start() because I don't know the exe file's location)

I want to run an exe file with c# but I can't use Process.Start() because I don't know the exe file's location.
I didn't start to writing so I don't have any code for now.
Use following :
string locateFile = "cmd.exe";
string environPath = Environment.GetEnvironmentVariable("Path");
string[] paths = environPath.Split(new char[] { ';' }).ToArray();
string filePath = "";
foreach (string path in paths)
{
string file = Directory.GetFiles(path, locateFile, SearchOption.TopDirectoryOnly).FirstOrDefault();
if (file != null)
{
filePath = file;
break;
}
}
if (filePath.Length > 0)
{
Console.WriteLine("File location : '{0}'", filePath);
}
else
{
Console.WriteLine("File not found");
}
Console.ReadLine();

C# I am trying to move a file from one directory, where I wont know what the name of the file is, to a new directory

I have the below throwing an exception: System.ArgumentException: 'Empty file name is not legal.
Parameter name: sourceFileName'
public bool ArchiveFile()
{
int fileCount = Directory.GetFiles(#"\\company\Archive\IN\InvoiceTest\Inbox\").Length;
DirectoryInfo diFileCheck = new DirectoryInfo(#"\\company\Archive\IN\InvoiceTest\Inbox\");
foreach (var fi in diFileCheck.GetFiles())
{
string strSourceFile = Path.GetFileName(#"\\company\Archive\\IN\InvoiceTest\Inbox\");
string strDestination =Path.Combine(#"\\company\ArchiveIN\InvoiceTest\Archive\", strSourceFile);
File.Move(strSourceFile, strDestination);
}
if (fileCount==0)
{
string strMessage = "No file found in directory: \n\n";
MessageBox.Show(strMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
else
{
return true;
}
}
Your problem is here:
foreach (var fi in diFileCheck.GetFiles())
{
string strSourceFile = Path.GetFileName(#"\\company\Archive\\IN\InvoiceTest\Inbox\");
string strDestination = Path.Combine(#"\\company\ArchiveIN\InvoiceTest\Archive\", strSourceFile);
File.Move(strSourceFile, strDestination);
}
Your fi is a FileInfo object, but you are not using it. Instead of using Path.GetFileName, use fi.Name.
See FileInfo
This reads all files from a source directory, and moves them to a target directory:
var filePaths = Directory.GetFiles("Source"); // get file paths from folder 'Source'
foreach (var filePath in filePaths)
{
var fileName = Path.GetFileName(filePath); // get only the name of the file
var targetPath = Path.Combine("Target", fileName); // create path to target directory 'Target' (including file name)
File.Move(filePath, targetPath); // move file from source path to target path
}

How to copy specific folder to new folder by clicking a button

One Question about coding (Visual Studio C# Windows form Application) There have Two folder: (Source and Target) and I build 1 button "Copy". In (Source) folder have random folders such "20190401", "20190402", "20190403", "20180401", "20170401" and "20160401". Every these folders have [10] ".txt" files. What is the coding if I only want to copy all "201904**" folders with [3] ".txt" files inside to "Target" folder?
Here my code for now, after I click a button the folder wouldn't copy. I guess there have some problem with this codes and I still not found it until. Hope you guys can help me, thank you.
*namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string FROM_DIR = "C:/Users/Desktop/Source/";
string TO_DIR = "C:/Users/Desktop/Target/";
DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
string directname = "201904";
string filename = ".txt";
foreach (DirectoryInfo newfile in fiDiskfiles)
{
try
{
if (newfile.Name == "2019")
{
foreach (DirectoryInfo direc in newfile.GetDirectories())
if (direc.Name.StartsWith(directname))
{
int count = 0;
foreach (FileInfo file in direc.GetFiles())
{
if (file.Name.EndsWith(filename))
{
count++;
}
}
if (count == 3)
{
DirectoryCopy(direc.FullName,Path.Combine(TO_DIR,direc.Name), true);
count = 0;
MessageBox.Show("success");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: "+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}
*}
By clicking the button, automatically copy all "201904**" folder and 3 ".txt files in (Source) folder to (target folder).
You didn't say which 3 txt files you want to copy so the code below copies all txt files, please explain how you select the files and I'll edit the code.
const string Source = #"C:\Users\Desktop\Source\";
const string Target = #"C:\Users\Desktop\Target\";
const string StartsWith = "201904";
const string FileType = "txt";
public static void Copy()
{
if (!Directory.Exists(Source)) //Check if the source directory exists
throw new Exception("Source directory is missing!");
Directory.CreateDirectory(Target); //If the target directory doesn't exists it will create one
var Directories = Directory.GetDirectories(Source, $"{StartsWith}*"); //Get directories which match the search pattern
for (int i = 0; i < Directories.Length; i++)
{
DirectoryInfo directory = new DirectoryInfo(Directories[i]);
Directory.CreateDirectory($"{Target}{directory.Name}"); //Create the directory in the target folder
var Files = Directory.GetFiles($"{Source}{directory.Name}", $"*.{FileType}"); //Get files
for (int j = 0; j < Files.Length; j++)
{
FileInfo file = new FileInfo(Files[j]);
File.Copy($"{Source}{directory.Name}" + #"\" + file.Name, $"{Target}{directory.Name}" + #"\" + file.Name); //Copy the file to the target folder
}
}
}
This code selects all directories which start with "201904" and all txt files inside them and copies it to the target folder.
EDIT: Fixed a mistake in the code

Taking path to IIS virtual catalog content

Im trying to take path to IIS virtual catalog but my solution returns me
file:///E:/Programy%20C#!Katalog2\Katalog2\MvcApplication1\Views\Home\jpg\1001\1\0
My code:
public ActionResult Searcher(string symbol, string dekoracja)
{
if (symbol != "" && dekoracja != "")
{
MyModel.Symbol = symbol;
MyModel.Dekorajca = dekoracja;
string path = Server.MapPath(Url.Content(#"~/Images/jpg/" + PathBuilder.Instance.pathBuilder(symbol, dekoracja)));
DirectoryInfo Dir = new DirectoryInfo(path);
try
{
FileInfo[] FileList = Dir.GetFiles("*jpg");
foreach (FileInfo fileInfo in FileList)
{
//tylko jpg ma wyswietlac do refaktoryzacji
MyModel.ImageList.Add(fileInfo.FullName);
}
}...
Im new in asp.net and I dont know how to take correct path (~/Vievs/Home/Jpg/...),i need it to put into image src. Symbol and Dekoracja are folder names given in parameter of ActionResult.
public class PathBuilder
{
public static readonly PathBuilder Instance = new PathBuilder();
public string pathBuilder(string Symbol, string Dekoracja)
{
return Symbol + #"\" + Dekoracja + #"\";
}
}
Your images should not be inside your /Views folder. Create a new folder in your app (say Images), then the code to generate the paths to be used in the src attribute of an <img> tag should be
string folder = String.Format("Images/{0}/{1}", symbol, dekoracja); // or whatever you call your folder
var path = Server.MapPath(folder);
FileInfo[] files = new DirectoryInfo(path).GetFiles(); // or GetFiles("*jpg") if it contains other image types
List<string> imageList = files.Select(x => String.Format("/{0}/{1}", folder, x.Name)).ToList();

Accessing USB Drives from 'Computer'

I'm trying to copy files over from the desktop to a USB drive programmatically. However, when trying to run this code, I am geting an error stating that part of the path could not be found:
if (dr == DialogResult.Yes)
{
string selected = comboBox1.GetItemText(comboBox1.SelectedItem);
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filefolder = #"\UpgradeFiles";
string fileLocation = filePath + filefolder;
if (!Directory.Exists(fileLocation))
{
Directory.CreateDirectory(fileLocation);
}
else if (Directory.Exists(fileLocation))
{
DirectoryInfo di = new DirectoryInfo(fileLocation);
FileInfo[] fileList = di.GetFiles();
foreach (FileInfo file in fileList)
{
string DrivePath = Environment.GetFolderPath(
Environment.SpecialFolder.MyComputer);
string CopyToDrive = comboBox1.Text;
file.CopyTo(DrivePath + CopyToDrive, false);
}
}
}
The combobox contains the selected drive letter. Am I approaching this wrong when trying to add "computer\driveletter"?
Your File.CopyTo(DrivePath + CopyToDrive, false) should be:
File.CopyTo(CopyToDrive + File.Name, false);
but with a bit of syntactic sugar like using Path.Combine or String.Format instead of just "+".
The issue is that File.CopyTo requires both the directory AND filename of the end location, when you're just providing the directory. This can be seen in the documentation for the method call here: https://msdn.microsoft.com/en-us/library/f0e105zt(v=vs.110).aspx

Categories