C# Error Index was outside the bounds of the array [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this code:
//other streamreader code
var splitsByLine = content.Split('\n');
foreach (var s in splitsByLine)
{
var nameAndSize = s.Split(',');
FileNameAndSizes.Add(nameAndSize[0], Convert.ToInt64(nameAndSize[1]));
}
foreach (var item in FileNameAndSizes)
{
if(File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "cleo", item.Key)))
{
FileInfo f = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "cleo", item.Key));
var s1 = f.Length;
if (s1 != item.Value)
{
MessageBox.Show(f.Name + " modified file, please change it to default");
}
}
}
When I run code, i have error in this code:
FileNameAndSizes.Add(nameAndSize[0], Convert.ToInt64(nameAndSize[1]));
Index was outside the bounds of the array. and something about 0x0.. I'm C# newbie, how can i fix it?
It's content value:
AnimModByxXx2o1o.cs, 18616
anims.cs, 18780
Dance.cs, 18661
emergencylights.cs, 32213
fps-de-limiter.cs, 17575
neon.cs, 19019
StreamMemFix.cs, 17560
sun.cs, 17662
WEATHERMENUE.cs, 18437
anim.cs, 17637
anim[0].cs, 20684
anim_0_.cs, 19392
anim1.cs, 18744
anim2.cs, 19012
Anim4.cs, 22900
anim228.cs, 19465
P.S I'm tested it with two files:
First file (current) is getting value from mysql, prints it, and then I need to read value with C# app
Second file (working) is create custom file write to it this content, and it's work ok :?

You need to do simple tests to ensure your values before try to work with them:
http://ideone.com/Iyle5C
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Test
{
public static void Main()
{
//other streamreader code
string[] splitsByLine = new string[] { "AnimModByxXx2o1o.cs, 18616",
"anims.cs, 18780",
"Dance.cs, 18661",
"emergencylights.cs, 32213",
"fps-de-limiter.cs, 17575",
"neon.cs, 19019",
"StreamMemFix.cs, 17560",
"sun.cs, 17662",
"WEATHERMENUE.cs, 18437",
"anim.cs, 17637",
"anim[0].cs, 20684",
"anim_0_.cs, 19392",
"anim1.cs, 18744",
"anim2.cs, 19012",
"Anim4.cs, 22900",
"anim228.cs, 19465",
"" };
if (splitsByLine != null && splitsByLine.Any()) // Test
{
foreach (string s in splitsByLine)
{
var nameAndSize = s.Split(',');
if (nameAndSize != null && nameAndSize.Any() && nameAndSize.Count() > 1) // Test
{
Console.WriteLine(String.Concat(nameAndSize[0], " - ", Convert.ToInt64(nameAndSize[1])));
//FileNameAndSizes.Add(nameAndSize[0], Convert.ToInt64(nameAndSize[1]));
}
}
}
}
}

Related

Check if cyclic string or not

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 hours ago.
Improve this question
Enter a string of characters S. Indicates whether the string S is cyclic or not.
For example S='abcdabcdabcdabcd' is cyclic.
My teacher want me to do this but i think it's too hard. I'm thinking using SplitString but it's just an idea and i dont know how to do. I'm very thankful if someone gives me help
using System;
using System.Collections;
public class MYCLASSNAME {
public static void Main(string[] args){
var str = "abcdabcdabcdabcd";
Console.Write(checkCyclicString(str));
}
static bool checkCyclicString (string str){
var checkString ="";
for(var i=0;i<str.Length-1;i++){
checkString= checkString+ str[i];
var countOfCycles =0;
var haveCycles = false;
for(var j=i+1;j<str.Length-checkString.Length+1;j= j+checkString.Length){
if(checkString==str.Substring(j,checkString.Length)){
haveCycles = true;
countOfCycles++;
}else{
haveCycles =false;
}
}
if(haveCycles && countOfCycles == Math.Ceiling((double)(str.Length/checkString.Length))-1){
return true;
}
}
return false;
}
}
check the cyclic behavior by creating substrigs and comparing them with all the parts of the given string

Unable to convert nested dictionaries from json back to c# using Json.Net [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am able to convert my nested dictionary to json but in attempting to use Json.Net.JsonNet.Deserialize<SortedDictionary<string, dynamic>>(js) it causes a null reference exception where js is loaded from a file containing: "{"Table":{"RowEntries":{}}}". Not sure what to do from here.
here is code to those it may concern:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (openFileDialog1.FileName != "" && openFileDialog1.FileName.EndsWith(".fdb"))
{
defaultPath = openFileDialog1.FileName;
js = #File.ReadAllText(openFileDialog1.FileName);
Console.WriteLine(js);
SortedDictionary<string, dynamic> cd;
try
{
cd = Json.Net.JsonNet.Deserialize<SortedDictionary<string, dynamic>>(js);
DatabaseFunct.currentData.Concat(cd);
//load tables
string[] mainTableKeys = DatabaseFunct.GetMainTableKeys();
foreach (string mainTableKey in mainTableKeys)
{
Program.mainForm.tabControl1.TabPages.Add(mainTableKey, mainTableKey);
}
//fileName = openFileDialog1.FileName.Remove(openFileDialog1.FileName.Length-4, openFileDialog1.FileName.Length);
Program.mainForm.label1.Visible = false;
//triggers event
Program.mainForm.tabControl1.SelectedIndex = 0;
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
else
{
System.Windows.Forms.MessageBox.Show("no valid file selected!");
}
}
Edit:
Was using the wrong Json.net package instead of the newtonsoft one.
Not sure what you are trying to achieve exactly, but based on provided json this should work:
class MyClass
{
public dynamic RowEntries { get; set; }
}
JsonNet.Deserialize<Dictionary<string, MyClass>>("{\"Table\":{\"RowEntries\":{}}}")

How do I "Unit Test" in C#? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
So I have this method in my project:
public static String MD5Hash(string TextToHash)
{
if ((TextToHash == null) || (TextToHash.Length == 0))
{
return String.Empty;
}
MD5 md5 = new MD5CryptoServiceProvider();
byte[] textToHash = Encoding.Default.GetBytes(TextToHash);
byte[] result = md5.ComputeHash(textToHash);
return System.BitConverter.ToString(result);
}
And I've tried testing like this:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BugMon;
namespace BugMonTesting
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
string pwd = "Password";
string expected = "DC-64-7E-B6-5E-67-11-E1-55-37-52-18-21-2B-39-64";
frmLogIn.MD5Hash(pwd);
Assert.AreEqual(pwd, expected);
}
}
}
But the string pwd does not seem to be passing through the Method when I run the test and stays as "Password".
What am I doing wrong?
Sorry if this is obvious but I've never had to use these tests before.
You're never doing anything with the return value from MD5Hash.
Try this:
string hash = frmLogIn.MD5Hash(pwd);
Assert.AreEqual(hash, expected);
Note that this will only work if MD5Hash returns a string formatted like the expected variable.

Read the lines in a text file after a certain line (c sharp)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Let's say I have a text file with this info:
...
Hey
all
this
is
my
question
...
All I want to take are the lines that contain "this" "is" & "my" , I don't know how far they are from the top nor how far they are from the bottom, all I know is that they are in that order and the lines they are surrounded by contain "all" and "question" . I already used a while loop to take everything up to "question", but I don't know how to indicate that it should neglect everything up to "this" (not including it). Could you help me?
the "easiest" route is to convert the file's lines into a list, and use generic collection methods to do what you want.
List<string> AllLines = File.ReadAllLines(yourpath).ToList();
int StartIndex = AllLines.IndexOf(ContainerStartString) + 1;
int EndIndex = AllLines.IndexOf(ContainerEndString) - 1;
List<string> MyLines = AllLines.GetRange(StartIndex, EndIndex);
Been doing it this way for 40 years
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENMAME = #"c:\temp\test.txt";
enum State
{
FIND_HEY,
GET_DATA,
FOUND_QUESTION
}
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENMAME);
string inputline = "";
State state = State.FIND_HEY;
while ((inputline = reader.ReadLine()) != null)
{
inputline = inputline.Trim();
if (inputline.Count() > 0)
{
switch (state)
{
case State.FIND_HEY :
if(inputline.ToUpper().Contains("HEY"))
{
state = State.GET_DATA;
}
break;
case State.GET_DATA :
if(inputline.ToUpper().Contains("QUESTION"))
{
state = State.FOUND_QUESTION;
}
else
{
Console.WriteLine(inputline);
}
break;
case State.FOUND_QUESTION :
break;
}
}
}
Console.ReadLine();
}
}
}
​

How do I get the duration of a video file using C#? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Any library in C# that allows me to do that?
google result for http://johndyer.name/post/2005/07/22/Retreiving-the-duration-of-a-WMV-in-C.aspx
using WMPLib; // this file is called Interop.WMPLib.dll
WindowsMediaPlayerClass wmp = new WindowsMediaPlayerClass();
IWMPMedia mediaInfo = wmp.newMedia("myfile.wmv");
// write duration
Console.WriteLine("Duration = " + mediaInfo.duration);
// write named attributes
for (int i=0; i<mediaInfo.attributeCount; i++)
{
Console.WriteLine(mediaInfo.getAttributeName(i) + " = " + mediaInfo.getItemInfo(mediaInfo.getAttributeName(i)) );
}
You can try this Extension method.
using Shell32;
public static class Extension
{
public static string GetLength(this FileInfo info)
{
var shell = new ShellClass();
var folder = shell.NameSpace(info.DirectoryName);
var item = folder.ParseName(info.Name);
return folder.GetDetailsOf(item, 27);
}
}
I hope following code snippet will help you :
using WMPLib;
// ...your code here...
var player = new WindowsMediaPlayer();
var clip = player.newMedia(filePath);
Console.WriteLine(TimeSpan.FromSeconds(clip.duration));
and don't forget to add the reference of wmp.dll which will be
present in System32 folder.

Categories

Resources