How to get Japanese font-names in Japanese? - c#

I have wrote some code to get the Font name out of ttf file. But when it run on English-windows OS, all the Japanese font return its name in English
Ex: instead of <リュウミン>.
I would like to get the the font name in Japanese when i run the program on my English-windows OS.
If you can give some advice, i will be appreciated!
I searched for System.Globalization namespace but it gets me no-where.
private void getFile_Click(object sender, EventArgs e)
{
fontFilePath.Text = openFolder();
}
private void print_Click(object sender, EventArgs e)
{
StringBuilder strb = new StringBuilder();
DirectoryInfo d = new DirectoryInfo(fontFilePath.Text);
//convert to jp
//System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("ja-JP", true);
//culture. = new System.Globalization.JapaneseCalendar();
FileInfo[] fil = d.GetFiles();
foreach (FileInfo _fil in fil)
{
PrivateFontCollection fonts = new PrivateFontCollection();
fonts.AddFontFile(_fil.FullName);
try { strb.Append(fonts.Families[0].Name).AppendLine(); }
catch (Exception ex) { }
}
FileStream fs = new FileStream(System.IO.Directory.GetCurrentDirectory() + "/path.txt" , FileMode.Create, FileAccess.ReadWrite);
StreamWriter strw = new StreamWriter(fs);
strw.Write(strb);
strw.Close();
strb.Clear();
}
private string openFolder()
{
FolderBrowserDialog fol = new FolderBrowserDialog();
if (fol.ShowDialog() == DialogResult.OK)
{
string folName = fol.SelectedPath;
return folName;
}
else
return "";
}

Related

DataGridView and copy image

I met one problem when I tried to copy file.
Error description
I worked with DataGridView and PictureBox.
Deguber of VS 2015 stopped me at
FileStream fs = File.Open(file, FileMode.Open);
in function CopyFile. I cant understand what's wrong i did.
This is some code (C#, .NET 4.5.1) from main form:
static string CopyFile(string file, string to)
{
FileInfo fileInfo = new FileInfo(file);
byte tmp = 0;
string temp = to + "\\" + fileInfo.Name;
FileStream newFile = File.Open(temp, FileMode.Create);
try
{
FileStream fs = File.Open(file, FileMode.Open);
for (int i = 0; i < fileInfo.Length; i++)
{
tmp = (byte)fs.ReadByte();
newFile.WriteByte(tmp);
}
fs.Close();
}
catch (FileNotFoundException ex)
{
MessageBox.Show("Не вдалося найти файл.");
}
newFile.Close();
return temp;
}
private void WriteNewUserToFile(User item, string pathToFile)
{
StreamWriter sw = new StreamWriter(File.Open(#pathToFile, FileMode.Append, FileAccess.Write));
sw.WriteLine(string.Format("{0}, {1}, {2}, {3}, {4}, {5}",
item.Id,
item.Image,
item.FirstName,
item.LastName,
item.Email,
item.Phone));
sw.Close();
}
private void btnAddUser_Click(object sender, EventArgs e)
{
AddUserForm dlg = new AddUserForm();
if (dlg.ShowDialog() == DialogResult.OK)
{
User item = dlg.NewUser;
item.Image = CopyFile(item.Image, "images");
WriteNewUserToFile(item, "data/users.dat");
users.Add(item);
//this.AddNewDataGridRow(item);
}
}
And some code of AddNewUserForm:
public User NewUser
{
get { return newUser; }
set { newUser = value; }
}
private void btnImage_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
txtImage.Text = dlg.FileName;
try
{
picboxImage.Image = Image.FromFile(txtImage.Text);
}
catch
{
picboxImage.Image = Image.FromFile(#"images\NoImg.bmp");
}
}
}
private void btnApply_Click(object sender, EventArgs e)
{
NewUser = new User
{
Id = Convert.ToInt32(txtId.Text),
LastName = txtLastName.Text,
FirstName = txtFirstName.Text,
Email = txtEmail.Text,
Phone = txtPhone.Text,
Image = txtImage.Text
};
this.DialogResult = DialogResult.OK;
}
If somebody need all project/code, click here (download VS project).
When you set the Image for the PictureBox using the following code, the call keeps the file handle open. So when you try to open the file again you encounter the exception.
picboxImage.Image = Image.FromFile(txtImage.Text);
According to this accepted answer, when the file handle is closed is unpredictable, in some cases, the handle won't be closed even if you explicitly close the Image.
So you may use the technique in that answer like this, to ensure the file handle is closed properly.
picboxImage.Image = Image.FromStream(new MemoryStream(File.ReadAllBytes(txtImage.Text)));

Always Getting Access Denied Error When I Write A File Inside Created Folder

I'm using windows (testing in 7 and 10)
And program creating folder first. After that, i want to write a file inside created folder. But always getting access denied error. I tried every directory in operating system. C: , programfiles, documents and project folder. Always i get that error message. Every Code is below, thank you.
app.manifest
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Create Folder Button Method
private void button2_Click(object sender, EventArgs e)
{
string path = "FullControl"; // Or C:\\FullControl > Doesn't matter same error
bool exist = System.IO.Directory.Exists(path);
if (!exist)
{
Directory.CreateDirectory(path);
}
var fInfo = new DirectoryInfo(path);
var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
var Security = fInfo.GetAccessControl(AccessControlSections.Access);
Security.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
}
Remove Folder ReadOnly
private void button3_Click(object sender, EventArgs e)
{
string path = "FullControl";
var fInfo = new DirectoryInfo(path);
FileAttributes f = fInfo.Attributes;
DecipherAttributes(path, f); //I dont now is it necessary ?
}
Create and Write File Button Method
private void button4_Click(object sender, EventArgs e)
{
string path = "FullControl";
string filePath = path + "FullControl\\Example.html";
if (!File.Exists(path))
{
try
{
StreamWriter tw = new StreamWriter(File.Open(path, FileMode.OpenOrCreate, FileAccess.Write), Encoding.UTF8);
tw.WriteLine("The very first line!");
tw.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else if (File.Exists(path))
{
StreamWriter tw = new StreamWriter(File.Open(path, FileMode.Open, FileAccess.ReadWrite), Encoding.UTF8);
tw.WriteLine("The next line!");
tw.Close();
}
}
Folder Attribute Method
public static void DecipherAttributes(String path ,FileAttributes f)
{
// To set use File.SetAttributes
File.SetAttributes(path, FileAttributes.ReadOnly);
if ((f & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
Console.WriteLine("ReadOnly");
// To remove readonly use "-="
f -= FileAttributes.ReadOnly;
if ((f & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
Console.WriteLine("ReadOnly");
else
Console.WriteLine("Not ReadOnly");
}
I change the code like this, and it's worked. I think the Path.Combine() is the solution. Thanks all comments.
String FolderPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
FolderPath = Path.Combine(FolderPath,"TestFolder");
String file = Path.Combine(FolderPath,"test.html");
if (!File.Exists(file))
{
try
{
StreamWriter tw = new StreamWriter(File.Open(file, FileMode.OpenOrCreate, FileAccess.Write), Encoding.UTF8);
tw.WriteLine("The very first line!");
tw.Close();
MessageBox.Show("File Created");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

How can I display MD5 and SHA-1 checksums of files within a listbox in C#?

The following can scan a directory, return all files within it and save that information to a .txt file, but how and where do I write the function to get the checksum of that file next to it?
Example: C:\Desktop\E01.txt | 32DC1515AFDB7DBBEE21363D590E5CEA
I would really appreciate any help with this.
private void btnScan_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
listBox1.Items.Clear();
string[] files = Directory.GetFiles(fbd.SelectedPath);
string[] dirs = Directory.GetDirectories(fbd.SelectedPath);
foreach (string file in files)
{
listBox1.Items.Add(file);
}
{
foreach (string dir in dirs)
{
listBox1.Items.Add(dir);
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
var saveFile = new SaveFileDialog();
saveFile.Filter = "Text (*.txt)|*.txt";
if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (var sw = new StreamWriter(saveFile.FileName, false))
foreach (var item in listBox1.Items)
sw.Write(item.ToString() + Environment.NewLine);
MessageBox.Show("This file was successfully saved.");
}
I've put together some code, to help you up. You will need to do the same for any other hash algorthim you may need.
just paste the snippet below, then add this modification:
foreach (string file in files)
{
listBox1.Items.Add(file + " | " + GetSHA1Hex(file));
}
Here you go:
public static string GetSHA1Hex(string fileName)
{
string result = string.Empty;
using (System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create("SHA1"))
using (System.IO.FileStream fs = System.IO.File.Open(fileName, System.IO.FileMode.Open))
{
byte[] b = sha1.ComputeHash(fs);
result = ToHex(b);
}
return result;
}
public static string[] HexTbl = Enumerable.Range(0, 256).Select(v => v.ToString("X2")).ToArray();
public static string ToHex(IEnumerable<byte> array)
{
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (var v in array)
s.Append(HexTbl[v]);
return s.ToString();
}
Note I copied the ToHex from here ->
byte[] to hex string

How to overwrite extracted zip file in C#, WinForms?

I have this code that backup and restore in C# using MS Access as its database. I finished doing the backup in zip format and now I want to restore the Zipped file. Any help will be much appreciated.
public void BackupDatabase(string dateToday)
{
string dbFileName = "dbCPS.accdb";
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory , dbFileName);
string backTimeStamp = Path.GetFileNameWithoutExtension(dbFileName) + "_" + dateToday + ".zip";// +Path.GetExtension(dbFileName);
string destFileName = backTimeStamp;// +dbFileName;
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
string PathtobackUp = fbd.SelectedPath.ToString();
destFileName = Path.Combine(PathtobackUp, destFileName);
//File.Copy(CurrentDatabasePath, destFileName, true);
using (var zip = new ZipFile())
{
zip.AddFile(dbFileName);
zip.Save(destFileName);
}
MessageBox.Show("Backup successful! ");
}
}
private void backupToolStripMenuItem1_Click(object sender, EventArgs e)
{
BackupDatabase(DateTime.Now.ToString("ddMMMyyyy_HH.mm"));
}
public void RestoreDatabase(string restoreFile)
{
string dbFileName = "dbCPS.accdb";
string pathBackup = restoreFile;
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory, dbFileName);
File.Copy(pathBackup, CurrentDatabasePath, true);
MessageBox.Show("Restore successful! ");
}
private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
openFileDialogBackUp.FileName = "dbCPS";
openFileDialogBackUp.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + #"Sauvegardes";
if (openFileDialogBackUp.ShowDialog() == DialogResult.OK)
RestoreDatabase(openFileDialogBackUp.FileName);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
This code extracts the zipped file but I dont know how to do the restore at the same time.
using (ZipFile zip = ZipFile.Read(restoreFile))
{
zip.ExtractAll(CurrentDatabasePath);
}
I've done it! For those who are in need of the code, here it is:
using (ZipFile zip = ZipFile.Read(pathBackup))
{
zip.ExtractAll(Environment.CurrentDirectory, ExtractExistingFileAction.OverwriteSilently);
}
You cannot overwrite directly the database while you are actively using it.
By actively I mean you have an OleDbConnection open on that database.
From your code above it is not possible to understand if you are in this situation, so the first thing to do is to search for all occurences of an OleDbConnection and check if they are closed correctly. If you have a global OleDbConnection that it is kept open for the lifetime of your application (a very bad practice), then you need to close it before trying to overwrite the accdb file
public void RestoreDatabase(string restoreFile)
{
string dbFileName = "dbCPS.accdb";
string extractedFile = Path.GetTempFileName();
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory, dbFileName);
using (ZipFile zip = ZipFile.Read(restoreFile))
{
// Extract to a temporary name built by the Framework for you....
zip.ExtractAll(extractedFile);
}
// Now, before copying over the accdb file, you need to be sure that there is no
// open OleDbConnection to this file, otherwise the IOException occurs because you
// cannot change that file while it is actively used by a OleDbConnection
// something like global_conn.Close(); global_conn.Dispose();
File.Copy(extractedFile, CurrentDatabasePath, true);
MessageBox.Show("Restore successful! ");
// and then reopen the connection
}
private void btn_UodateMembers_Click(object sender, EventArgs e)
{
if (!bwUpdateMembers.IsBusy)
{
bwUpdateMembers.RunWorkerAsync();
}
}
private string ExtractZip(FileInfo fi)
{
string extractTo = Path.Combine(fi.DirectoryName, Guid.NewGuid().ToString());
using (ZipFile zip = ZipFile.Read(fi.FullName))
{
foreach (ZipEntry ze in zip)
{
ze.Extract(extractTo, ExtractExistingFileAction.OverwriteSilently);
}
}
return extractTo;
}
public FileInfo GetLatestFile(DirectoryInfo di)
{
FileInfo fi = di.GetFiles()
.OrderByDescending(d => d.CreationTime)
.FirstOrDefault();
return fi;
}
private void bwUpdateMembers_DoWork(object sender, DoWorkEventArgs e)
{
string path = "C:\\Users\\Ghost Wolf\\Desktop\\zip";
DirectoryInfo di = new DirectoryInfo(path);
if (di != null)
{
FileInfo fi = GetLatestFile(di);
string folder = ExtractZip(fi);
MessageBox.Show("Your'e Files Have Been Extracted", "Notice", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
}
PLEASE TELL ME IF THIS WORKED FOR YOU!!

C# File - Read files from desktop and write them to a specific file

I created a System.Timers.Timer object with an interval of 5000 ms. On the Elapsed event of this timer, I'm searching the new PDF files which appeared on Desktop. If there are new PDF files, I add those to the specific file, but my program catch this error: The process cannot acces the file 'C:\Users\Admin\Desktop\StartupFiles.dat' because it is being used by another process.
Here is my code:
private readonly string fileName = Application.StartupPath + #"\StartupFiles.dat";
private readonly string sourceDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
void timerCheck_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
if (!File.Exists(fileName))
File.Create(fileName);
string[] PDFiles = Directory.GetFiles(sourceDirectory, "*.pdf", SearchOption.TopDirectoryOnly);
string[] textFile = File.ReadAllLines(fileName);
bool exist;
string addText = string.Empty;
foreach (string s in PDFiles) // Check the files from the desktop with the files from the fileName variabile folder
{
exist = false;
foreach (string c in textFile)
{
if (string.Compare(s, c) == 0)
{
exist = true;
break;
}
}
if (!exist)
{
addText += s + '\n';
}
}
if (!string.IsNullOrEmpty(addText)) // If a new PDF appeard on the desktop, save it to file
{
using (StreamWriter sw = File.AppendText(fileName))
{
sw.Write(addText);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Maybe I have to set a little delay between ReadAllLines and File.AppendText ?
#charqus, This should Work
if (!File.Exists(fileName))
File.Create(fileName).Dispose();
string[] PDFiles = Directory.GetFiles(sourceDirectory, "*.pdf", SearchOption.TopDirectoryOnly);
List<String> fileList = new List<String>();
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
using (BinaryReader r = new BinaryReader(fs))
{
fileList.Add(r.ReadString());
}
}
string[] textFile = fileList.ToArray();
Calling the Dispose method ensures that all the resources are properly released.

Categories

Resources