I need to get out of a String the Drive ,the directory and the extension. While the drive I go through I cant seem to get directory and extension to work.
namespace ConsoleApplication1
{
class GetMethods
{
public String GetDrive(String Path)
{
String Drive;
Drive = Path.Substring(0, 2);
Console.WriteLine("Drive: {0}", Drive);
return Drive;
}
public String GetDirectory(String Path)
{
Console.WriteLine("Directorul: ");
var start = Path.IndexOf(":") + 1;
var match2 = Path.Substring(start, Path.IndexOf(".") - start);
return Path;
}
public String GetExtension(String Path)
{
String Extension;
Extension = Path.Substring(0,3);
Console.WriteLine("Extensia: {0}", Extension);
return Extension;
}
}
class Program
{
static void Main(string[] args)
{
String Path;
GetMethods G = new GetMethods();
Console.WriteLine("Introduceti calea: ");
Path =Console.ReadLine();
Console.WriteLine("Calea introdusa este:");
Console.WriteLine(Path);
Console.WriteLine(G.GetDrive(Path));
Console.WriteLine(G.GetDirectory(Path));
Console.WriteLine(G.GetExtension(Path));
}
}
}
Use Path class to get all you want:
string path = #"C:\hello\world.txt";
var drive = Path.GetPathRoot(path); // "C:\"
var extension = Path.GetExtension(path); // ".txt"
var directory = Path.GetDirectoryName(path); // "C:\\hello"
You could use FileInfo class.
FileInfo fi = new FileInfo(path);
string ext = fi.Extension;
string dir = fi.DirectoryName;
Please reffer to: http://msdn.microsoft.com/en-us/library/system.io.fileinfo(v=vs.110).aspx
Related
I have a problem, i am trying to write a program that will copy a file with the same name from A to B and i want to change the exension from bk2 to bk3,4,5,6,7 or just rename the filename so the program can copy the file even if the same name allready exist.
I am very beginner in C# everything is dificult now.
Below the code
enter code here
static void Main(string[] args)
{
//path of file
string pathToOriginalFile = #"D:\C#\LOGS_PROG\SystemLog.bk2";
string extension = ".bk2";
//duplicate file path
string PathForDuplicateFile = #"D:\C#\Backup\Systemlog";
//provide source and destination file paths
File.Copy(pathToOriginalFile, PathForDuplicateFile + extension);
}
}
There is few tips.
You can use System.IO.Path.
path of file
string pathToOriginalFile = #"D:\C#\LOGS_PROG\SystemLog.bk2";
Where the file is located (D:\C#\LOGS_PROG) be careful, there is no \ at the end
string where = Path.GetDirectoryName(pathToOriginalFile);
THe name of the wile without its extension (SystemLog)
string name = Path.GetFileNameWithoutExtension(pathToOriginalFile);
its extension (.bk2)
string extension = Path.GetExtension(pathToOriginalFile);
The name and the extension (SystemLog.bk2)
string nameAndExtension = Path.GetFileName(pathToOriginalFile);
Now, if your purpose is to duplicate the file :
//path of file
string pathToOriginalFile = #"D:\C#\LOGS_PROG\SystemLog.bk2";
for (int i = 1; ; ++i)
{
// For example : D:\C#\LOGS_PROG\SystemLog (9).bk2 if there is the original + 8 copy
string pathToNewFile = Path.Combine(Path.GetDirectoryName(pathToOriginalFile), Path.GetFileNameWithoutExtension(pathToOriginalFile) + " (" + i + ")" + Path.GetExtension(pathToOriginalFile));
if (!File.Exists(pathToNewFile))
{
File.Copy(pathToOriginalFile, pathToNewFile);
break;
}
}
I separated the structure so you can see how it is built but you can use already known variables.
try this:
static void Main(string[] args)
{
//path of file
string pathToOriginalFile = #"D:\C#\LOGS_PROG\SystemLog.bk2";
string extension = ".bk2";
//duplicate file path
string PathForDuplicateFile = #"D:\C#\Backup\Systemlog";
//rename fileName if Exists
FixFileName(ref PathForDuplicateFile, extension);
//provide source and destination file paths
File.Copy(pathToOriginalFile, PathForDuplicateFile + extension);
}
static void FixFileName(ref string PathForDuplicateFile, string extention)
{
int i = 0;
while (true)
{
i++;
if (File.Exists(PathForDuplicateFile + extention))
PathForDuplicateFile += i;
else
break;
}
}
Problem solved.
The program copy the file and if the file exist it renames the extension.
Winndow runs it every day and so i got my autobackup
Thakns for the help!
static void Main(string[] args)
{
//path of file
string pathToOriginalFile = #"C:\Desktop\c#\Logging\Systemlog.bk66";
//duplicate file path
string PathForDuplicateFile = #"C:\\Desktop\c#\Systemlog";
//rename fileName if Exists
FixFileName(ref PathForDuplicateFile, ".bk");
if (File.ReadAllText(pathToOriginalFile).Length > 2000)
{
File.Copy(pathToOriginalFile, PathForDuplicateFile);
}
else
{
}
//provide source and destination file paths
}
static void FixFileName(ref string PathForDuplicateFile, string extention)
{
int i = 0;
while (true)
{
i++;
if (File.Exists(PathForDuplicateFile + extention))
extention += i;
else
break;
}
PathForDuplicateFile += extention;
}
}
How can I find path for tesseract.exe?
I tried this, but it has not found it, I used it for python.exe before with success:
var path = Environment.GetEnvironmentVariable("PATH");
string myPath = null;
foreach (var p in path.Split(new char[] { ';' }))
{
var fullPath = Path.Combine(p, "tesseract.exe");
if (File.Exists(fullPath))
{
myPath = fullPath;
break;
}
}
if (myPath != null)
{
Console.WriteLine(myPath);
}
else
{
throw new Exception("Couldn't find myPath on %PATH%");
}
So I tried:
var allExePaths =
from drive in Environment.GetLogicalDrives()
from exePath in Directory.GetFiles(drive, "*.exe", SearchOption.AllDirectories)
select exePath;
but it throws an error: Access to the path 'C:\Documents and Settings' is denied
public static string GetFullPath(string fileName)
{
if (File.Exists(fileName))
return Path.GetFullPath(fileName);
var values = Environment.GetEnvironmentVariable("PATH");
foreach (var path in values.Split(Path.PathSeparator))
{
var fullPath = Path.Combine(path, fileName);
if (File.Exists(fullPath))
return fullPath;
}
return null;
}
static string mydir = #"C:\Boba\bin\Release\ZipTest";
static string zipfile = string.Concat(mydir, ".zip");
using (ZipStorer zip = ZipStorer.Create(zipfile))
{
zip.AddDirectory(ZipStorer.Compression.Deflate, mydir, zipfile);
}
But after I unpack the archive, folders appear
Dir: Boba -> bin > Release > ZipTest > Files...
How do I add only the ZipTest folder?
I tried to do it like this:
DirectoryInfo d = new DirectoryInfo(mydir);
zip.AddDirectory(ZipStorer.Compression.Deflate, Path.GetFileName(d.FullName), Path.GetFileName(d.FullName), comment);
A Zip archive is created, and inside a folder called ZipTestZipTest, inside there are files and an empty archive called .zip.
How to make it just ZipTest inside the archive?
And so that there is no empty archive in the ZipTest folder?
Try set 3rd argument (_pathnameInZip) for .AddDirectory as empty string:
string dir = #"C:\Boba\bin\Release\ZipTest";
string zipFile = string.Concat(dir, ".zip");
string comment = "My ZipTest";
using (ZipStorer zip = ZipStorer.Create(zipFile))
{
zip.AddDirectory(ZipStorer.Compression.Deflate, dir, string.Empty, comment);
}
If you need without an internal directory, then you can do this:
public static void PackToZipWithoutInternalDir(string dir, string zipout, string comment = "")
{
if (Directory.Exists(dir) && !string.IsNullOrWhiteSpace(dir) && !string.IsNullOrWhiteSpace(zipout))
{
try
{
using var zip = ZipStorer.Create(zipout, comment); // true for stream
zip.EncodeUTF8 = true; // Text encoding
zip.ForceDeflating = true; // Force file compression
foreach (string listDir in Directory.EnumerateDirectories(dir, "*", SearchOption.TopDirectoryOnly))
{
// Add folders with files to the archive
zip.AddDirectory(ZipStorer.Compression.Deflate, listDir, string.Empty);
}
foreach (string listFiles in Directory.EnumerateFiles(dir, "*.*", SearchOption.TopDirectoryOnly))
{
// Add residual files in the current directory to the archive.
zip.AddFile(ZipStorer.Compression.Deflate, listFiles, Path.GetFileName(listFiles));
}
}
catch (Exception ex) { Console.WriteLine(ex); }
}
}
Use:
namespace ZipStorerEx
{
using System;
using System.IO;
public static class Program
{
private static readonly string CurrDir = Environment.CurrentDirectory;
private static readonly string BeginDir = Path.Combine(CurrDir, "YouDir");
private static readonly string ZipOut = $"{BeginDir}.zip";
[STAThread]
public static void Main()
{
Console.Title = "ZipStorerEx";
PackToZipWithoutInternalDir(BeginDir, ZipOut, "It's Good");
Console.ReadKey();
}
}
}
I need a copy file on folder to another folder and i'm use this
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string file in files)
{
folderBrowserDialog1.ShowDialog();
string xx = folderBrowserDialog1.SelectedPath;
folderBrowserDialog1.ShowDialog();
string yy = folderBrowserDialog1.SelectedPath;
File.Copy(xx, yy);
But is not working.
Why?
Try this code.
I assume you want to read a file then write it to new one.
Hope it helps.
string sourceFile;
string newFile = "C:\NewFile\NewFile.txt";
string fileToRead = "C:\ReadFile\ReadFile.txt";
bool overwriteExistingFile = true; //change to false if you want no to overwrite the existing file.
bool isReadSuccess = getDataFromFile(fileToRead, ref sourceFile);
if (isReadSuccess)
{
File.Copy(sourceFile, newFile, overwriteExistingFile);
}
else
{
Console.WriteLine("An error occured :" + sourceFile);
}
//Reader Method you can use this or modify it depending on your needs.
public static bool getDataFromFile(string FileToRead, ref string readMessage)
{
try
{
readMessage = "";
if (!File.Exists(FileToRead))
{
readMessage = "File not found: " + FileToRead;
return false;
}
using (StreamReader r = new StreamReader(FileToRead))
{
readMessage = r.ReadToEnd();
}
return true;
}
catch (Exception ex)
{
readMessage = ex.Message;
return false;
}
}
It seems that you do not use filenames in your source code.
I made an example. File copy function.
public void SaveStockInfoToAnotherFile(string sPath, string dPath, string filename)
{
string sourcePath = sPath;
string destinationPath = dPath;
string sourceFile = System.IO.Path.Combine(sourcePath, filename);
string destinationFile = System.IO.Path.Combine(destinationPath, filename);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}
//folderBrowserDialog1.ShowDialog();
//string xx = folderBrowserDialog1.SelectedPath;
//string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
//folderBrowserDialog1.ShowDialog();
//string yy = folderBrowserDialog1.SelectedPath;
//foreach (string file in files)
//{
// File.Copy(xx + "\\" + Path.GetFileName(file), yy + "\\" + Path.GetFileName(file));
I need to create a SSIS script to remove the date from file name. for example file name is: TestFile_122413.CSV I need to rename it to TestFile.CSV. I don't know how to keep file extension and how to deal with the date changes on file. I receive this file every day. Here is my code:
`public void Main()
// TODO: Add your code here
const string DIRECTORY_PATH = #"E:\ScriptsTest";
//const string FILE_NAME_TEMPLATE = "SSS_PROF_010113.CSV";
const string FILE_NAME_TEMPLATE = "*.CSV";
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
File.Move(filePath, filePath.Replace(FILE_NAME_TEMPLATE, FILE_NAME_TEMPLATE.Substring(0,8)));
}
}
}
}`
This should work. BTW, have you tried using the ForEach task? That may be simpler.
public void Main()
{
const string DIRECTORY_PATH = #"C:\temp\";
const string FILE_NAME_TEMPLATE = "*_??????.CSV";
int underscoreAt = 0;
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH,FILE_NAME_TEMPLATE);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
underscoreAt = filePath.LastIndexOf('_');
string newName = string.Format ("{0}.CSV", filePath.Substring(0, underscoreAt));
File.Move(filePath,newName );
}
}
}
}
Check out the SSIS File System Task. It has an operation to rename a file.
Here is a video on how it works.
Hope this helps!
Eric
Try this, it compiles but I haven't run it:
public class Foo
{
public void Main()
{
const string DIRECTORY_PATH = #"E:\ScriptsTest";
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
// Get the file name
string fileName = Path.GetFileName(filePath);
// Get the file extension
string fileExtension = Path.GetExtension(filePath);
// Get the file name without the date part
string fileTitle = fileName.Substring(0, fileName.IndexOf("_"));
File.Move(filePath, DIRECTORY_PATH + #"\" + fileTitle + "." + fileExtension);
}
}
}
}
}