How can I find tesseract.exe path with C#? - c#

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;
}

Related

Get files from a folder that I have created in Xamarin.Android

I want get all files from an external storage folder(wall_e_imgs)..Here are codes-
public void getImages()
{
var path1 = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath.ToString();
string path = System.IO.Path.Combine(path1, "wall_e_imgs");
//var files= System.IO.Directory.GetFiles(Android.OS.Environment.ExternalStorageDirectory.ToString() + "wall_e_imgs");
//var files = System.IO.Directory.GetFiles(path);
//string path = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/wall_e_imgs";
//File directory=new File(path);
Java.IO.File directory = new Java.IO.File(path);
Java.IO.File[] files = directory.ListFiles();//always count is 0 even though there are lot files there
foreach (var i in files)
{
FileInfo info = new FileInfo(i.Name);
if (info.Name.Contains("Wall_e"))
{
di.Add(new DownloadedImages { Path1 = info.DirectoryName, Name1 = info.FullName });
}
}
}
But it always give 0 files even though there are lot of files.
Try this
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "yourfoldername";
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
var filesList = Directory.GetFiles(folder);
foreach (var file in filesList)
{
var filename = Path.GetFileName(file);
}
Try something like this:
// Use whatever folder path you want here, the special folder is just an example
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "wall_e_imgs");
if (Directory.Exists(folderPath))
{
var files = Directory.EnumerateFiles(folderPath);
foreach (var file in files)
{
// Do your stuff
}
}
Please note that this uses the Directory class from System.IO, not Java.IO
ffilelist will contain a list of mp3 files in "/storage/emulated/0/Music/"
string phyle;
string ffilelist = "";
public void listfiles()
{
try
{
var path1 = "/storage/emulated/0/Music/";
var mp3Files = Directory.EnumerateFiles(path1, "*.mp3", SearchOption.AllDirectories);
foreach (string currentFile in mp3Files)
{
phyle = currentFile;
ffilelist = ffilelist + "\n" + phyle;
}
//playpath(phyle); // play the last file found
}
catch (Exception e9)
{
Toast.MakeText(ApplicationContext, "ut oh\n"+e9.Message , ToastLength.Long).Show();
}
}

Copy file code?

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));

How to remove guid from file name when creating zip file?

When user uploads multiple documents I am storing their files in my project like this:
Guid id;
id = Guid.NewGuid();
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(id + item.FileName));
item.SaveAs(filePath);
So files are saved like this in my project:
1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt
bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt
Now when creating zip files I am getting same name of this files when extracting zip files but I don't want guid in my file name after user downloads file.
However I have tried to remove guid from my file name but getting error System.IO.FileNotFoundException.
This is my code:
using (var zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
string[] str1 = str .Split(',');
foreach (var item in str1)
{
string filePath = Server.MapPath("~/Uploads/" + item.Substring(36));//as guid are of 36 digits
zip.AddFile(filePath, "files");
}
zip.Save(memoryStream);//Getting error here
}
ZipFile is throwing an exception because it can't find the file on disk as you have given it a name of a file that does not exist (by doing a .Substring()). To make it work you would have to rename the file using File.Copy with your new file name and then give that same file name to Zip.AddFile().
var orgFileName = "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt";
var newFileName = orgFileName.Substring (36);
File.Copy (orgFileName, newFileName, true);
zip.AddFile (newFileName);
You should use archive and ArchiveEntry. The rough code snipets how to do it (i don't test it):
using(var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) {
{
//using(var zip = new ZipFile()) {
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
//string[] str = str.Split(',');
foreach(var item in str) {
using(var entryStream = archive.CreateEntry("files/" + item.Substring(36)).Open()) {
string filePath = Server.MapPath("~/Uploads/" + item);
var content = File.ReadAllBytes(filePath);
entryStream.Write(content, 0, content.Length);
}
}
}
}
sample for using DotNetZip:
using (ZipFile zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" };
foreach(var item in str) {
string filePath = Server.MapPath("~/Uploads/" + item);
var content = File.ReadAllLines(filePath);
ZipEntry e = zip.AddEntry("files/" + item.Substring(36), content);
}
}
zip.Save(memoryStream);
}
Taking source from #kevin answer i have manage to solve this:
List<string> newfilename1 = new List<string>();
using (var zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
string[] str1 = str .Split(',');
foreach (var item in str1)
{
string filePath = Server.MapPath("~/Uploads/" + item);
string newFileName = Server.MapPath("~/Uploads/" + item.Substring(36));
newfilename1.Add(newFileName);
System.IO.File.Copy(filePath,newFileName);
zip.AddFile(newFileName,"");
}
zip.Save(memoryStream);
foreach (var item in newfilename1)
{
System.IO.File.Delete(item);
}
}

Filepath from a String in C#

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

C# return full path with GetFiles

Use this code for search files in directory:
FileInfo[] files = null;
string path = some_path;
DirectoryInfo folder = new DirectoryInfo(path);
files = folder.GetFiles("*.*", SearchOption.AllDirectories);
This return only filename and extension (text.exe). How to return full path to file(C:\bla\bla\bla\text.exe)?
If I use Directory.GetFiles("*.*"), this return full path. But if folder contains point in name(C:\bla\bla\test.0.1), result contains path to folder without file:
0 C:\bla\bla\bla\text.exe
1 C:\bla\bla\test.0.1
2 C:\bla\text.exe
etc.
FileInfo contains a FullName property, which you can use to retrieve full path to a file
var fullNames = files.Select(file => file.FullName).ToArray();
Check
This code on my machine:
FileInfo[] files = null;
string path = #"C:\temp";
DirectoryInfo folder = new DirectoryInfo(path);
files = folder.GetFiles("*.*", SearchOption.AllDirectories);
//you need string from FileInfo to denote full path
IEnumerable<string> fullNames = files.Select(file => file.FullName);
Console.WriteLine ( string.Join(Environment.NewLine, fullNames ) );
prints
C:\temp\1.dot
C:\temp\1.jpg
C:\temp\1.png
C:\temp\1.txt
C:\temp\2.png
C:\temp\a.xml
...
Full solution
The solution to your problem might look like this:
string path = #"C:\temp";
DirectoryInfo folder = new DirectoryInfo(path);
var directories = folder.GetDirectories("*.*", SearchOption.AllDirectories);
IEnumerable<string> directoriesWithDot =
directories.Where(dir => dir.Name.Contains("."))
.Select(dir => dir.FullName);
IEnumerable<string> filesInDirectoriesWithoutDot =
directories.Where(dir => !dir.Name.Contains("."))
.SelectMany(dir => dir.GetFiles("*.*", SearchOption.TopDirectoryOnly))
.Select(file => file.FullName);
Console.WriteLine ( string.Join(Environment.NewLine, directoriesWithDot.Union(filesInDirectoriesWithoutDot) ) );
Each FileInfo object has a FullName property.
But if folder contains point in name (C:\bla\bla\test.0.1), result contains path to folder without file
This is an entirely different issue with possibly diffeent answers/workarounds. Can you be more specific?
I cannot reproduce this.
You need to use FileInfo.
Directory.GetFiles("", SearchOption.AllDirectories).Select(file => new FileInfo(file).FullName);
public static IEnumerable<string> GetAllFilesRecursively(string inputFolder)
{
var queue = new Queue<string>();
queue.Enqueue(inputFolder);
while (queue.Count > 0)
{
inputFolder = queue.Dequeue();
try
{
foreach (string subDir in Directory.GetDirectories(inputFolder))
{
queue.Enqueue(subDir);
}
}
catch (Exception ex)
{
Console.Error.WriteLine("GetAllFilesRecursively: " + ex);
}
string[] files = null;
try
{
files = Directory.GetFiles(inputFolder);
}
catch (Exception ex)
{
Console.Error.WriteLine("GetAllFilesRecursively: " + ex);
}
if (files != null)
{
for (int i = 0; i < files.Length; i++)
{
yield return files[i];
}
}
}
}
you can try this :
void GetFiles()
{
DirectoryInfo d= new DirectoryInfo(strFolderPath);
//file extension for pdf
var files = d.GetFiles("*.pdf*");
FileInfo[] subfileInfo = files.ToArray<FileInfo>();
if (subfileInfo.Length > 0)
{
for (int j = 0; j < subfileInfo.Length; j++)
{
bool isHidden = ((File.GetAttributes(subfileInfo[j].FullName) & FileAttributes.Hidden) == FileAttributes.Hidden);
if (!isHidden)
{
string strExtention = th.GetExtension(subfileInfo[j].FullName);
if (strExtention.Contains("pdf"))
{
string path = subfileInfo[j].FullName;
string name = bfileInfo[j].Name;
}
}
}
}
You can use FileSystemInfo.FullName property.
Gets the full path of the directory or file.

Categories