Compare a string in if() - c#

I'm trying to compare a string in an if(string = ""), but it's apparently not the same
the string is "thisColor", it is defined by the content of a file.
I tried using Debug.Log(thisColor), the result is "rouge" but it's not recognized in if(thisColor == "rouge"). I also tried switch(thisColor) then case()...
Maybe it's the encoding..?
Here is the code snippet:
thisColor = "";
pixelSetup = GameObject.Find("Pixel" + setupPixelNumber.ToString());
setupPixelNumber += 1;
if (File.Exists("C:/PekmiIndustries/MVPlace/Pixel" + pixell + ".txt"))
{
thisColor = File.ReadAllText("C:/PekmiIndustries/MVPlace/Pixel" + pixell + ".txt");
}
else
{
File.Create("C:/PekmiIndustries/MVPlace/Pixel" + pixell + ".txt").Dispose();
}
string[] retourSuppr = new string[] { "\n" };
foreach(var c in retourSuppr)
{
thisColor = thisColor.Replace(c, string.Empty);
}
pixell = pixelSetup;
pixell.GetComponent<Renderer>().enabled = true;
Debug.Log("thisColor = |" + thisColor + "|");
if (thisColor != "")
{
Debug.Log(thisColor);
if (thisColor == "rouge")
{
Debug.Log("done.");
pixell.GetComponent<Renderer>().material.color = new Color(255f / 255f, 0, 0, 1);
thisColor = "";
}
else if (thisColor == "orangeF")
{
pixell.GetComponent<Renderer>().material.color = new Color(255f / 255f, 70f / 255f, 0 / 255f, 1);
thisColor = "";
}
else if (thisColor == "orange")
{
pixell.GetComponent<Renderer>().material.color = new Color(255f / 255f, 128f / 255f, 0 / 255f, 1);
thisColor = "";
}
else
{
Debug.Log("Passed");
}
thanks :)

This is because your file is encoded with something different than UTF-8, which is the default reading method used by ReadAllText
As said in this answer you can tell ReadAllText to use unicode instead.
File.ReadAllText("yourTextFile.txt", Encoding.Unicode);

i am not sure you "thisColor = File.ReadAllText("C:/PekmiIndustries/MVPlace/Pixel" + pixell + ".txt");" result,but i think the result contains space bar,so you can try this:
thisColor=thisColor.Replace(" ","")

If you are sure that "rouge" is among the words, just use Contains:
if (thisColor.Contains("rouge"))
{
// do something
}

Related

How to resolve exception Input string was not in a correct format when the string is "9f"?

The line:
currentFrameInt = System.Convert.ToInt32(currentFramestr);
In this case i see in currentFramestr the value " 9f"
Including three spaces in the start of the string.
The currentFramestr is part of updating a progressBar1:
if (strFFOUT.Contains("frame="))
{
currentFramestr = strFFOUT.Substring(7, 6);
currentFramestr = currentFramestr.Trim();
currentFrameInt = System.Convert.ToInt32(currentFramestr, 16);
}
string percentage = System.Convert.ToInt32((ProgressBar1.Value / ProgressBar1.Maximum * 100)).ToString() + "%";
ProgressBar1.Maximum = FCount + 1000;
ProgressBar1.Value = (currentFrameInt);
What i want to do is to update the progressBar value.
Maybe the whole method code will give more clue of what i want and the using with currentFramestr. In general i want to update the progressBar1 value.
private void Convert()
{
Control.CheckForIllegalCrossThreadCalls = false;
if (ComboBox1.SelectedIndex == 3)
{
strFFCMD = " -i \"" + InputFile + "\" \"" + OutputFile + "\"";
}
if (ComboBox1.SelectedIndex == 2)
{
strFFCMD = " -i " + (char)34 + InputFile + (char)34 +
" -c:v libx264 -s 1280x720 -pix_fmt yuv420p -qp 20 -profile high444-c:a libvo_aacenc -b:a 128k -ar 44100 -ac 2 " + OutputFile;
}
psiProcInfo.FileName = exepath;
psiProcInfo.Arguments = strFFCMD;
psiProcInfo.UseShellExecute = false;
psiProcInfo.WindowStyle = ProcessWindowStyle.Hidden;
psiProcInfo.RedirectStandardError = true;
psiProcInfo.RedirectStandardOutput = true;
psiProcInfo.CreateNoWindow = true;
prcFFMPEG.StartInfo = psiProcInfo;
prcFFMPEG.Start();
ffReader = prcFFMPEG.StandardError;
do
{
if (Bgw1.CancellationPending)
{
return;
}
Button5.Enabled = true;
Button3.Enabled = false;
strFFOUT = ffReader.ReadLine();
RichTextBox1.Text = strFFOUT;
if (strFFOUT.Contains("frame="))
{
currentFramestr = strFFOUT.Substring(7, 6);
currentFramestr = currentFramestr.Trim();
currentFrameInt = System.Convert.ToInt32(currentFramestr, 16);
}
string percentage = System.Convert.ToInt32((ProgressBar1.Value / ProgressBar1.Maximum * 100)).ToString() + "%";
ProgressBar1.Maximum = FCount + 1000;
ProgressBar1.Value = (currentFrameInt);
Label12.Text = "Current Encoded Frame: " + currentFrameInt;
Label11.Text = percentage;
} while (!(prcFFMPEG.HasExited || string.IsNullOrEmpty(strFFOUT)));
}
if it is supposed to be a hexadecimal number you give the function the base as the second parameter
ah and to get rid of the spaces do this first:
//Option 1: this removes all spaces before and after the string
currentFramestr = currentFramestr.Trim();
// Option 2: this removes all spaces in the string
Regex.Replace(currentFramestr, #"\s+", "");
// this will convert a hexadecimal number from string to int
currentFrameInt = System.Convert.ToInt32(currentFramestr, 16);
for the second option to work you need to include:
using System.Text.RegularExpressions;
second option is from here
You could use a Regex expression to extract any consecutive numeric digit from the start of your input string
....
currentFramestr = strFFOUT.Substring(7, 6).Trim();
Regex rx = new Regex(#"^\d+");
Match m = rx.Match(currentFramestr);
if(m.Success)
{
int currentFrameInt = System.Convert.ToInt32(m.Value);
....
}
To avoid the NullReferenceException you should add a check on ReadLine before trying to use its return value
do
{
....
strFFOUT = ffReader.ReadLine();
if(!string.IsNullOrEmpty(strFFOOUT))
{
RichTextBox1.Text = strFFOUT;
....
}
else
{
... end of data? break if you want to exit
// break;
}
} while (!prcFFMPEG.HasExited);

System.IO.File.WriteAllText outputs gibberish C#

I have a simple program in C# that is supposed to output a text file containing a sequence of character separated by commas. I also output the resulting sequence on the console and it looks fine, however, the text file is full of weird character and no commas.
This is the output :
㔳㌬ⰵⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰳⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰴⰰⰰⰰⰳⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰲⰱⰱⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰲⰰⰳⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰱⰱⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰰⰰⰳⰰⰴⰴⰴⰰⰰⰰⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰰⰰⰰⰰⰴⰴⰴⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰱⰱⰱⰱⰱⰲⰰⰲⰱⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰰⰰⰰⰰⰰⰵⰰⰵⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰲⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰵⰰⰵⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰲⰰⰰⰵⰰⰰⰰⰰⰰⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰵⰰⰰⰰⰴⰴⰰⰰⰰⰰⰱⰱⰱⰱⰱⰱⰰⰰⰱⰱⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰵⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰴⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰵⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰵⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰰⰰⰵⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰳⰰⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰵⰰⰰⰰⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰ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,0,0,0,0,0,0,0,0,1,4,4,0,0,4,4,4,4,0,
0,0,0,0,0,5,0,0,0,4,4,0,0,0,0,1,1,1,1,1,1,0,0,1,1,1,4,4,0,0,4,4,4,4,0,0,0,5,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,4,4,4,0,0,4,4,4,4,4,0,0,4,4,4,4,0,0,0,0,0,0,0,5,0,0,0,
0,0,0,0,0,0,0,4,4,4,4,0,0,0,0,0,0,0,0,0,4,4,4,4,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,
4,4,4,4,4,4,4,0,0,0,0,0,4,4,4,4,4,4,4,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,4,4,4,4,4,4,
4,4,4,0,0,3,0,4,4,4,4,4,4,4,0,0,0,0,0,5,0,0,0,4,4,4,4,0,0,4,4,4,4,4,4,4,4,0,0,0,
0,0,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,4,4,4,4,4,0,0,4,4,4,4,4,4,4,4,4,0,0,0,4,4,4,4,
4,4,4,4,0,0,0,0,0,0,0,0,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,4,4,4,4,4,4,4,4,4,4,0,
0,0,0,0,0,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
As I said, what is supposed to be outputted is the string that is directly passed into File.WriteAllText.
Am I missing something ? I don't understand what i'm doing wrong. It seems to be working sometimes, but with other string it does not. I can find no relation between the sequences that works and those that do not.
Here is the whole code, it's a simple program that read a bitmap and output the sequence depending on the pixel. It's badly & quickly written but it's supposed to work, i see no reason it shouldn't.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(args[0]);
Bitmap Map = new Bitmap(args[0]);
var MapRGB = Map.Clone(new Rectangle(0, 0, Map.Width, Map.Height), PixelFormat.Format32bppRgb);
int height = Map.Height;
int widht = Map.Width;
string MapText = height.ToString() + "," + widht.ToString() + ",";
for (int h = 0; h < height; h++)
{
for (int w = 0; w < widht; w++)
{
Color currentPixel =
MapRGB.GetPixel(w ,h );
if (currentPixel.ToArgb() == Color.White.ToArgb())
{
MapText = MapText + "0,";
}
if (currentPixel.ToArgb() == Color.Black.ToArgb())
{
MapText = MapText + "1,";
}
if (currentPixel.ToArgb() == Color.Gray.ToArgb())
{
MapText = MapText + "2,";
}
if (currentPixel.ToArgb() == Color.Yellow.ToArgb())
{
MapText = MapText + "3,";
}
if (currentPixel.ToArgb() == Color.Green.ToArgb())
{
MapText = MapText + "4,";
}
if (currentPixel.ToArgb() == Color.Red.ToArgb())
{
MapText = MapText + "5,";
}
Console.Clear();
Console.WriteLine(args[0] + " WROKING " + w.ToString() + " OF " + widht.ToString() + " IN " + h.ToString() + " OF " + height.ToString());
}
}
Console.Clear();
Console.Write(MapText);
System.IO.File.WriteAllText(Environment.CurrentDirectory + "/Map.bwn", MapText);
Console.ReadKey();
}
}
Not absolutely sure but could be an encoding issue. Use the other overload File.WriteAllText(String, String, Encoding) which takes a encoding type as argument like
File.WriteAllText(filePath, stringMessage, Encoding.UTF8);

DeviceCapabilities generates error: data is invalid

I want to get a printer's list of paper source, paper size, etc.
I slightly modified the codes from http://www.pinvoke.net/default.aspx/Enums/DeviceCapabilities.html?diff=y
The codes sometimes work, sometimes not.
The proplem is DeviceCapabilities(DeviceName, strPort, DeviceCapabilitiesFlags.DC_BINNAMES, (IntPtr)null, (IntPtr)null) returns -1. the last error is "data is invalid"
Restart computer may not solve the problem. Once getting the problem, next time maybe OK maybe not.
So what is the problem here?
ArrayList arrBinName;
string sError = "";
GetBins("\\Lindy-PC.MyCpmpany.local\HP LaserJet 4000 Series PCL 5", "LPT1", out arrBinName, out sError);
public static bool GetBins(string DeviceName, string strPort, out ArrayList BinName, out string strError)
{
strError = "";
BinName = new ArrayList();
IntPtr pAddr = default(IntPtr);
int offset = 0;
int nRes = DeviceCapabilities(DeviceName, strPort, DeviceCapabilitiesFlags.DC_BINNAMES, (IntPtr)null, (IntPtr)null); //Returns -1
if (nRes >= 0)
{
try
{
pAddr = Marshal.AllocHGlobal((int)nRes * 24);
nRes = DeviceCapabilities(DeviceName, strPort, DeviceCapabilitiesFlags.DC_BINNAMES, pAddr, (IntPtr)null);
if (nRes < 0)
{
strError = new Win32Exception(Marshal.GetLastWin32Error()).Message + "[" + DeviceName + ": " + strPort + ".DC_BINNAMES]";
return false;
}
offset = pAddr.ToInt32();
for (int i = 0; i < nRes; i++)
{
BinName.Add(Marshal.PtrToStringAnsi(new IntPtr(offset + i * 24)));
}
}
finally
{
Marshal.FreeHGlobal(pAddr);
}
}
else
strError = new Win32Exception(Marshal.GetLastWin32Error()).Message + "[" + DeviceName + ": " + strPort + ".DC_BINNAMES]";
return true;
}
As aggaton mentioned in his or her comment, DeviceCapabilities requires two calls in certain circumstances and retrieving bin names is one of them. You should first read the documentation for DeviceCapabilities.
Then go back and look at the sample code you used. You omitted a key step:
// BinNames
nRes = DeviceCapabilities(strDeviceName, strPort, DeviceCapabilitiesFlags.DC_BINNAMES, (IntPtr)null, (IntPtr)null);
pAddr = Marshal.AllocHGlobal((int)nRes * 24);
nRes = DeviceCapabilities(strDeviceName, strPort, DeviceCapabilitiesFlags.DC_BINNAMES, pAddr, (IntPtr)null);
if(nRes < 0)
{
strError = new Win32Exception(Marshal.GetLastWin32Error()).Message + "["+ strDeviceName +": "+ strPort +"]";
return false;
}
Notice that there are three calls to DeviceCapabilities in that code. You need all three. (I think the code would be clearer by making each call a separate line of code but that's a style issue.) The doc for DeviceCapabilities plus the sample code above should get you back on track.

How to add spaces dropdownlist values in MVC

I have a dropdownlist in a view like this,
<style type="text/css">
.form-control {
width: 50%;
padding: 10px;
}
#Html.DropDownListFor(x => x.FileName, ((IEnumerable<SelectListItem>)ViewData["Items"]), new { size = 15, #class = "form-control" , #style = "padding: 10px;"})
#Html.ValidationMessageFor(x => x.FileName)
The values look like below,
aaa.txt (2015-01-01) (0 B)
abcdedfff.txt (2015-02-01) (17 MB)
I want to add some spaces between these items so that it would look like below,
aaa.txt (2015-01-01) (0 B)
abcdedfff.txt (2015-02-01) (17 MB)
The controller has below code,
if (Directory.Exists(path))
{
files = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)
.Select(Path.GetFileName).OrderBy(f => f).ToArray();
}
long fSize = 0;
var count = 0;
var fileModified = "";
string fileSize = "";
string[] sizes = { "B", "KB", "MB", "GB" };
foreach (var filename in files)
{
var fileInfo = new FileInfo(path + "\\" + filename);
fSize = fileInfo.Length;
int order = 0;
while (fSize >= 1024 && order + 1 < sizes.Length)
{
order++;
fSize = fSize / 1024;
}
fileSize = String.Format("{0:0.##} {1}", fSize, sizes[order]);
fileModified = fileInfo.LastWriteTime.ToString("yyyy-MM-dd hh:mm:ss tt");
SelectListItem file = new SelectListItem() { Value = count.ToString(), Text = filename + " ( " + fileModified + " )" + " ( " + fileSize + " )" };
fileItems.Add(file);
count++;
}
How do I do that?
That's a lot of code to go into one of your Controller's methods. I would create different classes, maybe as services, that do all of that work for you.
I think the only way to do this is to create a service that creates the space for you.
You can modify the code you already have to create the space you want, or you can create another class that does it for you.
public class SelectListService
{
public IEnumerable<SelectListItem> GetData()
{
// Get your data
// create your spacing
// return your formatted SelectList
}
}
Then in your controller you just have to...
var selectListService = new SelectListService();
fileItems = selectListService.GetData();
Then of course pass it into your View however you're already doing it.
I think you have to get the highest length of your filename in your collection and than use right padding and space as padding character to your filename.
Try :
if (Directory.Exists(path))
{
files = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)
.Select(Path.GetFileName).OrderBy(f => f).ToArray();
}
long fSize = 0;
var count = 0;
var fileModified = "";
string fileSize = "";
string[] sizes = { "B", "KB", "MB", "GB" };
int longest_file_length = files.Max(a => a.Length);
foreach (var filename in files)
{
var fileInfo = new FileInfo(path + "\\" + filename);
fSize = fileInfo.Length;
int order = 0;
while (fSize >= 1024 && order + 1 < sizes.Length)
{
order++;
fSize = fSize / 1024;
}
fileSize = String.Format("{0:0.##} {1}", fSize, sizes[order]);
fileModified = fileInfo.LastWriteTime.ToString("yyyy-MM-dd hh:mm:ss tt");
string padded_file_name = filename.PadRight(longest_file_length, ' ');
SelectListItem file = new SelectListItem() { Value = count.ToString(), Text = padded_file_name + " ( " + fileModified + " )" + " ( " + fileSize + " )" };
fileItems.Add(file);
count++;
}
Also, you have to use monospace font so that the width of each character is same.
{ font-family:"Courier New", Courier, monospace; }
You could try alignment with String.Format like below:
SelectListItem file = new SelectListItem() { Value = count.ToString(), Text = String.Format("{0,-25} ({1}) ({2})", filename, fileModified, fileSize) };
You can see example at this link and read more about string formatting here.
Here is how you should modify your method if you want deservable output:
var maxFileNameLength = files.Max(x => x.Length);
foreach (var filename in files)
{
var fileInfo = new FileInfo(path + "\\" + filename);
fSize = fileInfo.Length;
int order = 0;
while (fSize >= 1024 && order + 1 < sizes.Length)
{
order++;
fSize = fSize / 1024;
}
fileSize = String.Format("{0:0.##} {1}", fSize, sizes[order]);
fileModified = fileInfo.LastWriteTime.ToString("yyyy-MM-dd hh:mm:ss tt");
fileNameWithSpaces = filename + string.Concat(Enumerable.Repeat(" ", maxFileNameLength + 1 - filename.Length));
SelectListItem file = new SelectListItem() { Value = count.ToString(), Text = fileNameWithSpaces + " ( " + fileModified + " )" + " ( " + fileSize + " )" };
fileItems.Add(file);
count++;
}
Ok, i check it. If you want to show your spaces in drop down you should use   rather that space. I updated the code
how about something like this
$("#selectId > option").each(function() {
var thistext=$(this).text();
var brindex=thistext.indexOf('(');
var firststring=thistext.substr(0,brindex)+" ";
var laststring=thistext.substr(brindex,thistext.length);
$(this).text(firsstring+laststring);
});
not tested but it should work

Saving Specific Lines to New Text Files

I am busy working with text files that are structured as seen below:
This is rainfall data in a continuous string each 5 characters after the date represent a day in the month.
0005880 W 1926 9-7777-7777-7777-7777-7777-7777-7777-7777-7777 117 130 64-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777
0005880 W 192610-7777-7777-7777-7777-7777-7777-7777-7777-7777 23-7777-7777-7777-7777 3-7777 226 462 71-7777-7777 157 76 15-7777-7777-7777-7777-7777-7777-7777
0005880 W 192611 3 20-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777 61 142-7777-7777-7777 8-7777-7777-7777-7777
0005880 W 192612-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777 132-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777-7777
The year and month are represented in (10, 4) and (14, 2) positions within the string.
My problem is that there is instances when the next line isn't the month that is meant to follow. I have written code that adds a line where a month of data is missing shown bellow.
public void findGapsToolStripMenuItem_Click(object sender, EventArgs e)
{
TabPage tp = new TabPage();
RichTextBox rtb = new RichTextBox();
rtb.Dock = DockStyle.Fill;
rtb.Multiline = true;
rtb.AcceptsTab = true;
rtb.WordWrap = false;
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
tp.Controls.Add(rtb);
tabControl1.TabPages.Add(tp);
string strfilename = openFileDialog1.FileName;
string[] lines = File.ReadAllLines(strfilename);
string[] pathArr = strfilename.Split('\\');
string[] fileArr = pathArr.Last().Split();
string filen = fileArr.Last().ToString();
tp.Text = filen;
int pyear = 0;
int pmon = 0;
int imon = 0;
int iyear = 0;
foreach (string line in lines)
{
string missing = "-9999";
string year = line.Substring(10, 4);
string mon = line.Substring(14, 2);
iyear = Convert.ToInt32(year);
imon = Convert.ToInt32(mon);
if (pyear == 0)
{
pyear = iyear;
pmon = imon;
rtb.AppendText(line + "\n");
}
else
{
int pt = pyear * 12 + pmon;
int t = iyear * 12 + imon;
if ((pt + 1) == t)
{
rtb.AppendText(line + "\n");
}
else
{
rtb.AppendText("Missing Months =" + (t - pt) + "\n");
}
if (line.Contains(missing))
{
rtb.AppendText("Missing Days" + "\n");
}
pyear = iyear;
pmon = imon;
}
rtb.SelectAll();
rtb.SelectionAlignment = HorizontalAlignment.Left;
rtb.SelectionFont = new Font("Consolas", 10);
}
}
}
}
My Question is, Is there a way of exporting all the lines before the missing month or day to a text file named the start date to the date before the missing month or day. E.g 1926.9.1926.10.txt. Then continuing through the file for the next section of data before the next missing month or day. So essentially ending up with multiple text documents containing Years or Months of Data with out gaps. I would also like it to automatically create a folder with the Station Number which is the first 14 characters (i.E 0005880 W) where all the text files will be created in.
Update
public void findGapsToolStripMenuItem_Click(object sender, EventArgs e)
{
TabPage tp = new TabPage();
RichTextBox rtb = new RichTextBox();
rtb.Dock = DockStyle.Fill;
rtb.Multiline = true;
rtb.AcceptsTab = true;
rtb.WordWrap = false;
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
tp.Controls.Add(rtb);
tabControl1.TabPages.Add(tp);
string strfilename = openFileDialog1.FileName;
string[] lines = File.ReadAllLines(strfilename);
string[] pathArr = strfilename.Split('\\');
string[] fileArr = pathArr.Last().Split();
string filen = fileArr.Last().ToString();
string pat = #"C:\Test\" + filen;
System.IO.Directory.CreateDirectory(pat);
int i;
tp.Text = filen;
int pyear = 0;
int pmon = 0;
int imon = 0;
int iyear = 0;
int j = 1;
foreach (string line in lines)
{
using (StreamWriter sw = new StreamWriter(#"C:\Test\" + filen+".txt"))
{
string missing = "-9999";
string year = line.Substring(10, 4);
string mon = line.Substring(14, 2);
iyear = Convert.ToInt32(year);
imon = Convert.ToInt32(mon);
string filepath = #"C:\Test\" + year + "." + mon+".txt";
if (pyear == 0)
{
File.CreateText(filepath);
pyear = iyear;
pmon = imon;
rtb.AppendText(line + "\n");
sw.WriteLine(line);
}
else
{
File.CreateText(filepath);
int pt = pyear * 12 + pmon;
int t = iyear * 12 + imon;
if ((pt + 1) == t)
{
rtb.AppendText(line + "\n");
sw.WriteLine(line);
}
else
{
string path = pat + "\\" + year + "." + mon + ".txt";
File.CreateText(path);
rtb.AppendText("Missing Months =" + (t - pt) + "\n");
}
if (line.Contains(missing))
{
string path = pat + "\\" + year + "." + mon + ".txt";
File.CreateText(path);
rtb.AppendText("Missing Days" + "\n");
}
pyear = iyear;
pmon = imon;
}
rtb.SelectAll();
rtb.SelectionAlignment = HorizontalAlignment.Left;
rtb.SelectionFont = new Font("Consolas", 10);
}
}
}
}
}
You can create files using the various methods of the System.IO.File class:
http://msdn.microsoft.com/en-us/library/system.io.file.aspx
This class includes methods for creating files as well as writing out arbitrary text lines to one.
You can create directories using the methods of the System.IO.Directory class:
http://msdn.microsoft.com/en-us/library/system.io.directory.aspx
UPDATE: Here is some pseudocode
startdate = null
foreach(line in the input file)
{
currentdate = date on this line in the input file
if(startdate == null)
{
// We are at the start of a new block of dates
startdate = currentdate
add this line to a list (in memory)
}
else if(currentdate == lastdate in the list + 1 month)
{
// This date is consecutive
add this line to a list (in memory)
}
else
{
// We have a gap in the data
write out all data in the list to file named <startdate>-<lastdate in list>
startdate = currentdate
add this line to the list (which we've just emptied)
}
}
write out the last file
This is just very rough and ready, but should indicate the kind of way you need to think to write this code. One thing to be clear on, if you want to name the file using the end date of a block of dates you can't create the file until you've found the last line in that block so you need to store the lines in memory until you find a gap in the dates, or the end of your input file.

Categories