I can't use french characters - c#

I m developing a c# hangman game for a competition.
I generate some words that have french characters and my vs2015 is not supporting them. For example when it generates "mûre" word instead of "û" there is displayed a "?".
I tried to go to Tools->Options->International Settings and there to download French language pack. I runned it and nothing happened. My displayed options there are only "English" and "Same as Microsoft Windows". ( I restarted my pc after installation);
Here is my function that generates the word:
private void generateRandomWord_Survival() {
Random rand;
rand = new Random();
if (!playSurvival) return;
StreamReader filereader;
int lineNumber = 0;
filereader = new StreamReader(#"survival_easy.txt");
if (survival_level == "easy") {
filereader = new StreamReader(#"survival_easy.txt");
lineNumber = File.ReadAllLines(#"survival_easy.txt").Length;
} else if (survival_level == "medium") {
filereader = new StreamReader(#"survival_medium.txt");
lineNumber = File.ReadAllLines(#"survival_medium.txt").Length;
} else if (survival_level == "hard") {
filereader = new StreamReader(#"survival_hard.txt");
lineNumber = File.ReadAllLines(#"survival_medium.txt").Length;
}
int line = rand.Next(1, lineNumber);
string text = String.Empty;
for (int i = 1; i <= line; i++) {
text = filereader.ReadLine();
}
filereader.Close();
word = text.ToCharArray();
initLabelSetup();
initLabelSetup();
}

Try using a different encoding when you read the file.
File.ReadAllLines(#"survival_easy.txt", Encoding.GetEncoding("iso-8859-1"));

Related

Split one string and put it in two arrays

I'd like to split several strings of a text file into two strings each (example: car;driver). I do not know how to put the first word in array1 and the second word in array2. So I tried with an if query for a semicolon to put every single letter of word1 in array1 and the same with the second word to put them back together to the words later.
But I think it's too complicated what I've done and I am stuck now, lol.
Here I show a piece of my code:
private void BtnShow_Click(object sender, EventArgs e)
{
LibPasswords.Items.Clear();
string path = "passwords.txt";
int counter = 0;
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (StreamReader reader = new StreamReader(fs))
{
while (reader.ReadLine() != null)
{
counter++;
}
//for (int i = 0; i < counter; i++)
//{
// var Website = reader.ReadLine().Split(';').Select(x => new String[] { x });
// var Passwort = reader.ReadLine().Split(';').Select(y => new String[] { y });
// LibPasswords.Items.Add(String.Format(table, Website, Passwort));
//}
string[] firstWord = new string[counter];
string[] lastWord = new string[counter];
int i = 0;
int index = 0;
while (reader.Peek() >= 0)
{
string ch = reader.Read().ToString();
if (ch != ";")
{
firstWord[i] = ch;
i++;
}
else
{
index = 1;
}
while (reader.Peek() >= 0)
{
??????????????????????????????????
}
}
}
}
Sorry for my English, it's not my mother tongue.
As you don't know in advance how many lines there are, it is more convenient to use a List<string> instead of a string[]. A List will automatically increase its capacity as needed.
You can use the string.Split method to split the string at the ';' into an array. If the resulting array has the correct number of parts, you can add those parts to the Lists.
List<string> firstWord = new List<string>();
List<string> lastWord = new List<string>();
string fileName = #"C:\temp\SO61715409.txt";
foreach (string line in File.ReadLines(fileName))
{
string[] parts = line.Split(new char[] { ';' });
if (parts.Length == 2)
{
firstWord.Add(parts[0]);
lastWord.Add(parts[1]);
}
}

iTextSharp .NET PDF - unable to change PDF Producer

I am using iTextSharp product to change the PDF properties as follows.
I am unable to change the "PDF Producer" property at all. Please suggest, where am i getting wrong.
The code line
info["Producer"] = "My producer";
is not working as it should be.
string sourcePath = tbPath.Text;
IList<string> dirs = null;
string pdfName = string.Empty;
string OutputPath = string.Empty;
DirectoryInfo di = new DirectoryInfo(sourcePath);
DirectoryInfo dInfo = Directory.CreateDirectory(sourcePath + "\\" + "TempDir");
OutputPath = Path.Combine(sourcePath,"TempDir");
dirs = Directory.GetFiles(di.FullName, "*.pdf").ToList();
for (int i = 0; i <= dirs.Count - 1; i++)
{
try
{
PdfReader pdfReader = new PdfReader(dirs[i]);
using (FileStream fileStream = new FileStream(Path.Combine(OutputPath, Path.GetFileName(dirs[i])),
FileMode.Create,
FileAccess.Write))
{
PdfStamper pdfStamper = new PdfStamper(pdfReader, fileStream);
Dictionary<string, string> info = pdfReader.Info;
info["Title"] = "";
info["Author"] = "";
info["Producer"] = "My producer"; ////THIS IS NOT WORKING..
pdfStamper.MoreInfo = info;
pdfStamper.Close();
pdfReader.Close();
}
You can only change the producer line if you have a license key. A license key needs to be purchased from iText Software. Instructions on how to apply the license key are sent along with that key.
If you want to use iText for free, you can't change the producer line. See the license header of every file in the open source version of iText:
* In accordance with Section 7(b) of the GNU Affero General Public License,
* a covered work must retain the producer line in every PDF that is created
* or manipulated using iText.
For your info: iText Group has successfully sued a German company that changed the producer line without purchasing a license. You can find some documents related to this case here: IANAL: What developers should know about IP and Legal (slide 57-62)
By the way, I won a JavaOne Rockstar award with this talk: https://twitter.com/itext/status/704278659012681728
Summarized: if you don't have a commercial license for iText, you can not legally change the producer line in iText. If you have a commercial license, you need to apply the license key.
If you are using known producer, you can replace bytes in PDF file.
You need producer to be at least length of your Company (or producer replacement text) name.
In this example I'm assuming that producer has at least 20 chars. You have to determine that by editing PDF file with text editor.
Before using this check licence for the program used to create PDF
Here is an example in C#.
// find producer bytes: "producer... " in array and replace
// them with "COMPANY", and after fitth with enough spaces (code: 32)
var textForReplacement = "producer";
var bytesForReplacement = System.Text.Encoding.UTF8.GetBytes(textForReplacement);
var newText = "COMPANY";
var newBytes = System.Text.Encoding.UTF8.GetBytes(newText);
var result = this.Search(pdf, bytesForReplacement);
if (result > -1)
{
var j = 0;
for (var i = result; i < result + 20; i++)
{
// if we have new bytes, then replace them
if (i < result + newBytes.Length)
{
pdf[i] = newBytes[j];
j++;
}
// if not, fill spaces (32)
else
{
pdf[i] = 32;
}
}
}
return pdf;
}
int Search(byte[] src, byte[] pattern)
{
int c = src.Length - pattern.Length + 1;
int j;
for (int i = 0; i < c; i++)
{
if (src[i] != pattern[0]) continue;
for (j = pattern.Length - 1; j >= 1 && src[i + j] == pattern[j]; j--) ;
if (j == 0) return i;
}
return -1;
}

text file not updated after write c# Windows Phone 8

I'm trying to write string data into a text file in a Windows Phone 8 app but the text file just would not be updated.
I'm writing with the codes below
public void update_file(Contact_List[] list) //Write to file
{
using (FileStream fs = new FileStream(#"contact_list.txt", FileMode.Open))
{
using (StreamWriter sw = new StreamWriter(fs))
{
for (int x = 0; x < list.Length; x++)
{
sw.WriteLine(list[x].first_name);
sw.WriteLine(list[x].last_name);
sw.WriteLine(list[x].number);
sw.WriteLine(list[x].email);
sw.WriteLine(list[x].company);
sw.WriteLine(list[x].favorite);
sw.WriteLine(list[x].group);
}
sw.Close();
}
fs.Close();
}
}
Where Contact_List is my custom struct which contains the following string:
public string first_name;
public string last_name;
public string email;
public string number;
public string company;
public string favorite;
public string group;
The program itself could be run without any error which including the reading and even during the program the written contents could be display in the list box but the written contents would never be updated in the actual file.
The reading part is the following
public class All_Contact : common_func //Counting number of lines in the file
{
public int count_lines()
{
int counter = 0;
var str = Application.GetResourceStream(new Uri(#"contact_list.txt", UriKind.Relative));
StreamReader sr = new StreamReader(str.Stream);
while (sr.ReadLine() != null)
{
counter++;
}
sr.Close();
sr.Dispose();
str.Stream.Close();
str.Stream.Dispose();
return counter;
}
public string[][] read_content (int ln) //Read and pick up the actual contents
{
string[][] temp = null;
int lines = ln;
temp = new string[lines / 7][];
var str = Application.GetResourceStream(new Uri(#"contact_list.txt", UriKind.Relative));
StreamReader sr = new StreamReader(str.Stream);
for (int x = 0; x < (lines / 7); x++)
{
temp[x] = new string[7];
for (int y = 0; y < 7; y++)
{
temp[x][y] = sr.ReadLine();
}
}
sr.Close();
sr.Dispose();
str.Stream.Close();
str.Stream.Dispose();
return temp;
}
I'm very new to programming with Windows Phone 8 application so I don't have any idea how are the things working in background therefore any detailed explanation will be appreciated.
Thank You

Auto Incrementing file names?

I have a list of files like so
abc.txt
pas.txt
tempr.txt
What I would like to do is to append english alphabets to theese file names ..
the result should look like this
abc_a.txt
pas_b.txt
tempr_c.txt
This process should continue till the last character (i.e 'z'). if there are more files then the file names would become
abc_a.txt
pas_b.txt
tempr_c.txt
.................
filename_z.txt
anotherfilename_a001.txt
Notice that the counter was again reset to the first character except an integer was attached to it.
This is the code that i have right now. Please note that it is NOT working ..
string alphabets= "abcdefghijklmnopqrstuvwxyz";
List<string> filenames = new List<string>();
filenames.Add("test1.txt");
filenames.Add("newfile.cs");
filenames.Add("test2.txt");
filenames.Add("newfile2.cs");
string currentFileNmae = string.Empty;
foreach(string s in filenames) {
char usedAlphabet = new char();
for(int i = 0;i<=alphabets.Length-1;i+=11) {
usedAlphabet.Dump();
alphabets[i].Dump();
if(usedAlphabet != alphabets[i] )
{
if(currentFileNmae!= s)
{
string.Format("{0}--{1}",s,alphabets[i]).Dump();
usedAlphabet = alphabets[i];
currentFileNmae = s;
}
}
break;
}
}
I am part of a team that's building a file renamer tool for our internal purposes and hence i need this code. This is part of the our enumertation functionality that we have planned.
Please suggest.
thanks
Try starting here:
using System.Diagnostics;
using System.IO;
string filename = #"C:\Foo\Bar.txt";
for (int count = 0; count < 100; count++)
{
char letter = (char)((int)'a' + count % 26);
string numeric = (count / 26) == 0 ? "" : (count / 26).ToString("000");
Debug.Print(Path.GetFileNameWithoutExtension(filename) + "_" + letter + numeric + Path.GetExtension(filename));
}
Substitute your own loop to go through the filenames and use Path to manipulate the pieces/parts of the names.
The renaming, IIRC, can be handled by File.Move. Surround it with a try/catch to implement the name collision logic.
Had no coffee yet, but this should do.
List<string> files = new List<string>();
int charIndex = 0;
int numericIndex = -1;
foreach (var file in files.Select(path => new FileInfo(path)))
{
// Create new Filename - This may needs some tuning
// to really remove only the extension ad the end
// It doesnt take care of things like
// file.bmp.bmp.bmp ...
string newFileName = String.Format("{0}_{1}{2}.{3}",
file.FullName.Replace(file.Extension,String.Empty),
(char)(charIndex++ + 97),
(numericIndex > -1 ? String.Format("{0:D4}", numericIndex) : String.Empty),
file.Extension);
// Rename the File
file.MoveTo(newFileName);
// Increment Counters.
if (charIndex > 25)
{
charIndex = 0;
numericIndex++;
}
}
You can try something like this
const string directory = #"C:\\wherever";
string[] fiNames = new string[]{ "abc", "pas", "etc",};
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
int x = 0;
string ending = "";
for(int i = fiNames.Count()-1; i>=0; i--)
{
if(x%26==0)
{
x=0
if( ending=="")
ending="1";
else
ending=(System.Convert.ToInt32(ending)+1).ToString();
}
System.IO.File.Move(directory+fiNames[i], fiNames[i]+alphabet[x].ToString()+ending);
x++;
}

Remove Duplicate Lines From Text File?

Given an input file of text lines, I want duplicate lines to be identified and removed. Please show a simple snippet of C# that accomplishes this.
For small files:
string[] lines = File.ReadAllLines("filename.txt");
File.WriteAllLines("filename.txt", lines.Distinct().ToArray());
This should do (and will copy with large files).
Note that it only removes duplicate consecutive lines, i.e.
a
b
b
c
b
d
will end up as
a
b
c
b
d
If you want no duplicates anywhere, you'll need to keep a set of lines you've already seen.
using System;
using System.IO;
class DeDuper
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: DeDuper <input file> <output file>");
return;
}
using (TextReader reader = File.OpenText(args[0]))
using (TextWriter writer = File.CreateText(args[1]))
{
string currentLine;
string lastLine = null;
while ((currentLine = reader.ReadLine()) != null)
{
if (currentLine != lastLine)
{
writer.WriteLine(currentLine);
lastLine = currentLine;
}
}
}
}
}
Note that this assumes Encoding.UTF8, and that you want to use files. It's easy to generalize as a method though:
static void CopyLinesRemovingConsecutiveDupes
(TextReader reader, TextWriter writer)
{
string currentLine;
string lastLine = null;
while ((currentLine = reader.ReadLine()) != null)
{
if (currentLine != lastLine)
{
writer.WriteLine(currentLine);
lastLine = currentLine;
}
}
}
(Note that that doesn't close anything - the caller should do that.)
Here's a version that will remove all duplicates, rather than just consecutive ones:
static void CopyLinesRemovingAllDupes(TextReader reader, TextWriter writer)
{
string currentLine;
HashSet<string> previousLines = new HashSet<string>();
while ((currentLine = reader.ReadLine()) != null)
{
// Add returns true if it was actually added,
// false if it was already there
if (previousLines.Add(currentLine))
{
writer.WriteLine(currentLine);
}
}
}
For a long file (and non consecutive duplications) I'd copy the files line by line building a hash // position lookup table as I went.
As each line is copied check for the hashed value, if there is a collision double check that the line is the same and move to the next. (
Only worth it for fairly large files though.
Here's a streaming approach that should incur less overhead than reading all unique strings into memory.
var sr = new StreamReader(File.OpenRead(#"C:\Temp\in.txt"));
var sw = new StreamWriter(File.OpenWrite(#"C:\Temp\out.txt"));
var lines = new HashSet<int>();
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
int hc = line.GetHashCode();
if(lines.Contains(hc))
continue;
lines.Add(hc);
sw.WriteLine(line);
}
sw.Flush();
sw.Close();
sr.Close();
I am new to .net & have written something more simpler,may not be very efficient.Please fill free to share your thoughts.
class Program
{
static void Main(string[] args)
{
string[] emp_names = File.ReadAllLines("D:\\Employee Names.txt");
List<string> newemp1 = new List<string>();
for (int i = 0; i < emp_names.Length; i++)
{
newemp1.Add(emp_names[i]); //passing data to newemp1 from emp_names
}
for (int i = 0; i < emp_names.Length; i++)
{
List<string> temp = new List<string>();
int duplicate_count = 0;
for (int j = newemp1.Count - 1; j >= 0; j--)
{
if (emp_names[i] != newemp1[j]) //checking for duplicate records
temp.Add(newemp1[j]);
else
{
duplicate_count++;
if (duplicate_count == 1)
temp.Add(emp_names[i]);
}
}
newemp1 = temp;
}
string[] newemp = newemp1.ToArray(); //assigning into a string array
Array.Sort(newemp);
File.WriteAllLines("D:\\Employee Names.txt", newemp); //now writing the data to a text file
Console.ReadLine();
}
}

Categories