How to find items in a ListBox? - c#

I am creating an application where I have a ListBox which has items that are read in from a text file using StreamReader. I have created a search form but I'm not sure what to do next. Can anyone give me some suggestions please? Here is my code:
My code for the ListBox (sorry it's so long)
public partial class frmSwitches : Form
{
public static ArrayList switches = new ArrayList();
public static frmSwitches frmkeepSwitches = null;
public static string inputDataFile = "LeckySafe.txt";
const int numSwitchItems = 6;
public frmSwitches()
{
InitializeComponent();
frmkeepSwitches = this;
}
private void btnDevices_Click(object sender, EventArgs e)
{
frmDevices tempDevices = new frmDevices();
tempDevices.Show();
frmkeepSwitches.Hide();
}
private bool fileOpenForReadOK(string readFile, ref StreamReader dataIn)
{
try
{
dataIn = new StreamReader(readFile);
return true;
}
catch (FileNotFoundException notFound)
{
MessageBox.Show("ERROR Opening file (when reading data in) - File could not be found.\n"
+ notFound.Message);
return false;
}
catch (Exception e)
{
MessageBox.Show("ERROR Opening File (when reading data in) - Operation failed.\n"
+ e.Message);
return false;
}
}
private bool getNextSwitch(StreamReader inNext, string[] nextSwitchData)
{
string nextLine;
int numDataItems = nextSwitchData.Count();
for (int i = 0; i < numDataItems; i++)
{
try
{
nextLine = inNext.ReadLine();
if (nextLine != null)
nextSwitchData[i] = nextLine;
else
{
return false;
}
}
catch (Exception e)
{
MessageBox.Show("ERROR Reading from file.\n" + e.Message);
return false;
}
}
return true;
}
private void readSwitches()
{
StreamReader inSwitches = null;
Switch tempSwitch;
bool anyMoreSwitches = false;
string[] switchData = new string[numSwitchItems];
if (fileOpenForReadOK(inputDataFile, ref inSwitches))
{
anyMoreSwitches = getNextSwitch(inSwitches, switchData);
while (anyMoreSwitches == true)
{
tempSwitch = new Switch(switchData[0], switchData[1], switchData[2], switchData[3], switchData[4], switchData[5]);
switches.Add(tempSwitch);
anyMoreSwitches = getNextSwitch(inSwitches, switchData);
}
}
if (inSwitches != null) inSwitches.Close();
}
public static bool fileOpenForWriteOK(string writeFile, ref StreamWriter dataOut)
{
try
{
dataOut = new StreamWriter(writeFile);
return true;
}
catch (FileNotFoundException notFound)
{
MessageBox.Show("ERROR Opening file (when writing data out)" +
"- File could not be found.\n" + notFound.Message);
return false;
}
catch (Exception e)
{
MessageBox.Show("ERROR Opening File (when writing data out)" +
"- Operation failed.\n" + e.Message);
return false;
}
}
public static void writeSwitches()
{
StreamWriter outputSwitches = null;
if (fileOpenForWriteOK(inputDataFile, ref outputSwitches))
{
foreach (Switch currSwitch in switches)
{
outputSwitches.WriteLine(currSwitch.getSerialNo());
outputSwitches.WriteLine(currSwitch.getType());
outputSwitches.WriteLine(currSwitch.getInsDate());
outputSwitches.WriteLine(currSwitch.getElecTest());
outputSwitches.WriteLine(currSwitch.getPatId());
outputSwitches.WriteLine(currSwitch.getNumDevice());
}
outputSwitches.Close();
}
if (outputSwitches != null) outputSwitches.Close();
}
private void showListOfSwitches()
{
lstSwitch.Items.Clear();
foreach (Switch b in switches)
lstSwitch.Items.Add(b.getSerialNo()
+ b.getType() + b.getInsDate()
+ b.getElecTest() + b.getPatId() + b.getNumDevice());
}
My code for the search form:
private void btnSearch_Click(object sender, EventArgs e)
{
frmSearchSwitch tempSearchSwitch = new frmSearchSwitch();
tempSearchSwitch.Show();
frmkeepSwitches.Hide();
}

If using a List<T> and lambda is not possible for you then go no farther.
Here I use a List<T> for the data source of a ListBox and mocked up data as where the data comes from is not important but here I am focusing on searching on a property within a class where a select is used to index the items then the where searches in this case) for a specific item, if found the index is used to move to the item. No code present for if not located as this is easy for you to do if the code here is something that is doable for you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace ListBoxSearch_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
var results =
((List<Item>)ListBox1.DataSource)
.Select((data, index) => new
{ Text = data.SerialNumber, Index = index })
.Where((data) => data.Text == "BB1").FirstOrDefault();
if (results != null)
{
ListBox1.SelectedIndex = results.Index;
}
}
private void Form1_Load(object sender, EventArgs e)
{
var items = new List<Item>() {
new Item {Identifier = 1, SerialNumber = "AA1", Type = "A1"},
new Item {Identifier = 2, SerialNumber = "BB1", Type = "A1"},
new Item {Identifier = 3, SerialNumber = "CD12", Type = "XD1"}
};
ListBox1.DisplayMember = "DisplayText";
ListBox1.DataSource = items;
}
}
/// <summary>
/// Should be in it's own class file
/// but done here to keep code together
/// </summary>
public class Item
{
public string SerialNumber { get; set; }
public string Type { get; set; }
public int Identifier { get; set; }
public string DisplayText
{
get
{
return SerialNumber + " " + this.Type;
}
}
}
}

Related

Event Handler Fires Twice When Plugging/Unplugging USB Serial Port

I am writing a program which is supposed to detect when a USB serial device is plugged in and then log on to the new com port. The code below works wonderfully, but I have noticed in debugging the code and stepping through it that the event handler "DetectChange" fires twice. I'm not sure that this is normal, or an action of the debugger.
In any case, the code works, but I am new at event handling and I would like to make sure that I am not going to cause any issues as I add more code to actually read and write from the serial port.
(I got some of this code from stackoverflow, but I have misplaced my paper with names for attribution. If you see your code below, my heartfelt thanks.)
using System;
using System.IO.Ports;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
using System.Threading;
namespace SerialTest
{
public partial class Form1 : Form
{
SerialMethods serialMethods = new SerialMethods();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
loadCmdBox();
}
private void CmdBoxPort_SelectedIndexChanged(object sender, EventArgs e)
{
handleComPort();
}
private void handleComPort()
{
// Set the right port for the selected item.
// The portname is based on the "COMx" part of the string (SelectedItem)
string item = CmdBoxPort.SelectedItem.ToString();
// Search for the expression "(COM" in the "selectedItem" string
if (item.Contains("(COM"))
{
// Get the index number where "(COM" starts in the string
int indexOfCom = item.IndexOf("(COM");
// Set PortName to COMx based on the expression in the "selectedItem" string
// It automatically gets the correct length of the COMx expression to make sure
// that also a COM10, COM11 and so on is working properly.
string PortName = item.Substring(indexOfCom + 1, item.Length - indexOfCom - 2);
if (serialMethods._serialPort.IsOpen)
{
serialMethods._serialPort.Close();
serialMethods.Connect(PortName);
label5.Text = "Active Port: " + PortName;
}
else
{
serialMethods.Connect(PortName);
label5.Text = PortName;
}
}
else
return;
}
private void loadCmdBox()
{
// Get all serial (COM)-ports you can see in the devicemanager
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\cimv2",
"SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");
// Sort the items in the combobox
CmdBoxPort.Sorted = true;
// Add all available (COM)-ports to the combobox
foreach (System.Management.ManagementObject queryObj in searcher.Get().Cast<ManagementObject>())
{
CmdBoxPort.Items.Add(queryObj["Caption"]);
}
SerialPortService.PortsChanged += (sender1, changedArgs) => DetectChange(changedArgs.EventType);
label2.Text = "";
label3.Text = "";
label4.Text = "";
}
protected Task<Task> getSerPorts()
{
CmdBoxPort.Text = "";
CmdBoxPort.Update();
if (!String.IsNullOrEmpty(CmdBoxPort.Text))
{
handleComPort();
return Task.FromResult(Task.CompletedTask);
}
else
{
loadCmdBox();
return Task.FromResult(Task.CompletedTask);
}
}
private void ExitButton_Click(object sender, EventArgs e)
{
SerialPortService.CleanUp();
this.Close();
}
private void RefreshButton_Click(object sender, EventArgs e)
{
refresh();
}
protected Task<Task> refresh()
{
label2.Text = "";
label3.Text = "";
label4.Text = "";
CmdBoxPort.Items.Clear();
getSerPorts();
return Task.FromResult(Task.CompletedTask);
}
protected virtual void DetectChange(EventType changedArgs)
{
if (changedArgs == EventType.Insertion)
{
try
{
Task tr = (Task)Invoke(new Action( () => { getSerPorts(); }));
Task rr = (Task)Invoke(new Action(() => { refresh(); }));
}
catch (Exception ex) { MessageBox.Show("Exception at insertion invoke method " + ex, "Exception", MessageBoxButtons.OK); }
}
else if (changedArgs == EventType.Removal)
{
try
{
Task tr = (Task)Invoke(new Action( () => { getSerPorts(); }));
Task rr = (Task)Invoke(new Action(() => { refresh(); }));
}
catch (Exception ex) { MessageBox.Show("Exception at removal invoke method " + ex, "Exception", MessageBoxButtons.OK); }
}
return;
}
}
public static class SerialPortService
{
private static SerialPort _serialPort;
private static string[] _serialPorts;
private static ManagementEventWatcher arrival;
private static ManagementEventWatcher removal;
private static readonly SerialMethods SD = new SerialMethods();
static SerialPortService()
{
_serialPorts = SerialPort.GetPortNames();
MonitorDeviceChanges();
}
public static void CleanUp()
{
arrival.Stop();
removal.Stop();
}
public static event EventHandler<PortsChangedArgs> PortsChanged;
private static void MonitorDeviceChanges()
{
try
{
var deviceArrivalQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
var deviceRemovalQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
arrival = new ManagementEventWatcher(deviceArrivalQuery);
removal = new ManagementEventWatcher(deviceRemovalQuery);
arrival.EventArrived += (o, args) => RaisePortsChangedIfNecessary(EventType.Insertion);
removal.EventArrived += (sender, eventArgs) => RaisePortsChangedIfNecessary(EventType.Removal);
// Start listening for events
arrival.Start();
removal.Start();
}
catch (ManagementException err)
{
MessageBox.Show("Management exception = " + err, "Info", MessageBoxButtons.OK);
}
}
private static void RaisePortsChangedIfNecessary(EventType eventType)
{
lock (_serialPorts)
{
var availableSerialPorts = SerialPort.GetPortNames();
if (eventType == EventType.Insertion)
{
var added = availableSerialPorts.Except(_serialPorts).ToArray();
_serialPorts = availableSerialPorts;
PortsChanged.Raise(null, new PortsChangedArgs(eventType, added));
}
else if (eventType == EventType.Removal)
{
var removed = _serialPorts.Except(availableSerialPorts).ToArray();
_serialPorts = availableSerialPorts;
PortsChanged.Raise(null, new PortsChangedArgs(eventType, removed));
}
}
}
public static void Raise<T>(this EventHandler<T> handler, object sender, T args) where T : EventArgs
{
handler?.Invoke(sender, args);
}
}
public enum EventType
{
Insertion,
Removal,
}
public class PortsChangedArgs : EventArgs
{
private readonly EventType _eventType;
private readonly string[] _serialPorts;
public PortsChangedArgs(EventType eventType, string[] serialPorts)
{
_eventType = eventType;
_serialPorts = serialPorts;
}
public string[] SerialPorts => _serialPorts;
public EventType EventType => _eventType;
}
}
Just took a short look at this. It seems like getSerPorts() will always execute loadCmdBox() (CmdBoxPort.Text = ""; ... if (!String.IsNullOrEmpty(CmdBoxPort.Text))) that will attach a new event handler (previous attached event handlers will not be removed by attaching a new one).
You should either remove the existing event handler befor attaching a new one or only attach the event handler once.

ListBoxes won't display data from StreamReader text files

I have the .txt files inside the project's debug folder but the listboxes still won't display any of the data.
I've already missed the due date for this project, I just have a very unhelpful professor and I'd love to learn what I did wrong. Thanks!
The overview of what I'm trying to do here is:
Display delimited data into three listboxes from three text files. When a user clicks on an item in the listbox, one line of additional data (an ID) will be displayed in a textbox underneath that listbox. All three listboxes are shown on the same form and all data is delimited using the same character.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace LabDay2Modified
{
struct CustomersNames
{
public string custID;
public string firstName;
public string lastName;
public string accountID;
}
struct AccountNumbers
{
public string acctID;
public string accountType;
public string accountNumber;
public string accountAmt;
}
struct LoanInfo
{
public string loanID;
public string loanYears;
public string loanIntRate;
public string loanAmt;
public string customerID;
public string loanType;
}
public partial class Form1 : Form
{
private List<CustomersNames> customerList = new List<CustomersNames>();
private List<AccountNumbers> accountList = new List<AccountNumbers>();
private List<LoanInfo> loanList = new List<LoanInfo>();
public Form1()
{
InitializeComponent();
}
private void ReadCustFile()
{
try
{
StreamReader inputFile;
string line;
CustomersNames entry = new CustomersNames();
char[] delim = { ',' };
inputFile = File.OpenText("customers.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.custID = tokens[0];
entry.firstName = tokens[1];
entry.lastName = tokens[2];
entry.accountID = tokens[3];
customerList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReadAcctFile()
{
try
{
StreamReader inputFile;
string line;
AccountNumbers entry = new AccountNumbers();
char[] delim = { ',' };
inputFile = File.OpenText("accounts.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.acctID = tokens[0];
entry.accountNumber = tokens[1];
entry.accountType = tokens[2];
entry.accountAmt = tokens[3];
accountList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReadLoanFile()
{
try
{
StreamReader inputFile;
string line;
LoanInfo entry = new LoanInfo();
char[] delim = { ',' };
inputFile = File.OpenText("loans.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.customerID = tokens[0];
entry.loanID = tokens[1];
entry.loanType = tokens[2];
entry.loanYears = tokens[3];
entry.loanIntRate = tokens[4];
entry.loanAmt = tokens[5];
loanList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void CustInfo()
{
foreach(CustomersNames entry in customerList)
{
customerListBox.Items.Add(entry.custID + " " + entry.firstName + " " + entry.lastName);
}
}
private void AcctInfo()
{
foreach (AccountNumbers entry in accountList)
{
accountListBox.Items.Add(entry.accountNumber + " " + entry.accountType + " " + entry.accountAmt);
}
}
private void LoansInfo()
{
foreach (LoanInfo entry in loanList)
{
loanListBox.Items.Add(entry.loanID + " " + entry.loanType + " " + entry.loanYears+" "+entry.loanIntRate+" "+entry.loanAmt);
}
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void customerListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = customerListBox.SelectedIndex;
customerAccountID.Text = "Account ID: " + customerList[index].accountID;
}
private void loanListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = loanListBox.SelectedIndex;
loanCustomerID.Text = "Customer ID: " + loanList[index].customerID;
}
private void accountListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = accountListBox.SelectedIndex;
accountAccountID.Text = "Account ID: " + accountList[index].acctID;
}
private void Form1_Load(object sender, EventArgs e)
{
ReadCustFile();
CustInfo();
ReadAcctFile();
AcctInfo();
ReadLoanFile();
LoansInfo();
}
}
}
You can use the following .txt file to see if it works for you.
Then, you will get the following result.
Besides, you can set the similar style for other txt files.

UserAppDataReigistry not persisting

I have the following class to persist my camera settings.
using System;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.XtraEditors.Camera;
public class CameraDeviceHelper
{
public string DeviceMoniker;
public string DeviceName;
public int DeviceResolutionWidth;
public int DeviceResolutionHeight;
const string kDeviceName = "CameraDeviceName";
const string kDeviceMoniker = "CameraDeviceMoniker";
const string kDeviceResolutionWidth = "CameraDeviceResolutionWidth";
const string kDeviceResolutionHeight = "CameraDeviceResolutionHeight";
public bool SaveCameraDevice(CameraControl cc)
{
try
{
DeviceMoniker = cc.Device.DeviceMoniker;
DeviceName = cc.Device.Name;
DeviceResolutionWidth = cc.Device.Resolution.Width;
DeviceResolutionHeight = cc.Device.Resolution.Height;
Application.UserAppDataRegistry.SetValue(kDeviceName, DeviceName);
Application.UserAppDataRegistry.SetValue(kDeviceMoniker, DeviceMoniker);
Application.UserAppDataRegistry.SetValue(kDeviceResolutionWidth, DeviceResolutionWidth);
Application.UserAppDataRegistry.SetValue(kDeviceResolutionHeight, DeviceResolutionHeight);
return true;
}
catch (Exception)
{
return false;
}
}
public bool RestoreCameraDevice(CameraControl cc)
{
try
{
DeviceName = Application.UserAppDataRegistry.GetValue(kDeviceName, DeviceName).ToString();
DeviceMoniker =Application.UserAppDataRegistry.GetValue(kDeviceMoniker, DeviceMoniker).ToString();
DeviceResolutionWidth = (int) Application.UserAppDataRegistry.GetValue(kDeviceResolutionWidth, DeviceResolutionWidth);
DeviceResolutionHeight = (int)Application.UserAppDataRegistry.GetValue(kDeviceResolutionHeight, DeviceResolutionHeight);
var moniker = new DevExpress.Data.Camera.CameraDeviceInfo(DeviceMoniker, DeviceName);
cc.Device = new CameraDevice(moniker);
var sz = new Size(DeviceResolutionWidth,DeviceResolutionHeight);
cc.Device.Resolution = sz;
if (cc.Device.Resolution.Width != sz.Width)
{ MessageBox.Show("Not set");}
cc.Start();
return true;
}
catch (Exception)
{
return false;
}
}
}
}
The persisting works while the application runs.
However when I restart the application the settings are lost.
I call the methods in my form's load and FormClosed events
private void Camera_Load(object sender, EventArgs e)
{
textEdit1.Text = PhotoCaption;
cameraDeviceHelper = new CameraDeviceHelper();
try
{
cameraDeviceHelper.RestoreCameraDevice(cameraControl1);
}
catch (Exception)
{
// probably first time... so just dont complain
throw;
}
}
private void Camera_FormClosed(object sender, FormClosedEventArgs e)
{
cameraDeviceHelper.SaveCameraDevice(cameraControl1);
}
The solution is not to have an * in the AssemblyVersion
otherwise every time the application is built the registry key will change.

C# Using SoundPlayer to Pause and Resume

I am another person dabbling with C# and wanting to create a simple audio application that plays wav files loaded into the program via an upload program. My issue is that I need to get whatever audio file currently being played to pause with the track timer of the audio file being used when I start the audio file again via my Play button. I already have a global timer, 'baseTimer', that I think I can use to set the audio file, that was stopped, track duration point. However I do not know how to accomplish this nor do I really know how to use all of the mci commands yet.
I have displayed all of my code for my main application... I also have read that I may need to utilize threading, but I've also read that it would be impossible to set an audio files track duration with a thread.
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
System.Timers.Timer baseTimer = new System.Timers.Timer();
List<string> PlayList = new List<string>();
List<byte> PlayList_byte;
int soundNum = 0;
private string music_PATH { get; set; }
private string talk_PATH { get; set; }
private byte Pause_TIME { get; set; }
private string Pause_RADIO { get; set; }
bool isStopped = new bool();
bool isPaused = new bool();
[DllImport("winmm.dll")]
private static extern uint mciSendString(string command, StringBuilder returnValue, int returnLength, IntPtr winHandle);
public static int GetSoundLength(string fileName)
{
StringBuilder lengthBuf = new StringBuilder(32);
mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);
mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);
mciSendString("close wave", null, 0, IntPtr.Zero);
int length = 0;
int.TryParse(lengthBuf.ToString(), out length);
return length;
}
private void SetPath()
{
music_PATH = #"..\\..\\commercial\list.txt";
talk_PATH = #"..\\..\\main\list.txt";
StreamReader myReader;
using (myReader = new StreamReader(music_PATH))
{
while (myReader.Peek() != -1)
{
string read = myReader.ReadLine();
PlayList.Add(read);
}
}
using (myReader = new StreamReader(talk_PATH))
{
while (myReader.Peek() != -1)
{
string read = myReader.ReadLine();
PlayList.Add(read);
}
myReader.Close();
}
foreach (string sound in PlayList)
{
soundNum++;
}
}
private string CurrentSound()
{
try
{
Random _randx = new Random();
int pick = _randx.Next(0, soundNum);
string currentaudio = PlayList[pick];
Pause_RADIO = currentaudio;
return currentaudio;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
return null;
}
string _SelectedSound = "";
private string _Sound(string currentradio, string pattern)
{
foreach (Match entry in Regex.Matches(currentradio, pattern))
{
_SelectedSound = entry.Value.ToString();
}
if (_SelectedSound == "music")
{
return "commercial";
}
else if (_SelectedSound == "talk")
{
return "main";
}
return null;
}
private void _SetTimer(string currentradio, string pattern)
{
baseTimer.Interval = GetSoundLength(#"..\\..\\" + pattern + #"\" + currentradio);
}
private bool isRepeat(string lastradio, string currentradio)
{
if (lastradio == currentradio)
{
return true;
}
else
{
return false;
}
}
private void baseTimerElasped(object sender, ElapsedEventArgs e)
{
Radio.FrmMain play = new Radio.FrmMain();
play.PlayPlayer();
}
private void PlayPlayer()
{
MediaPlayer wavplayer;
try
{
if (soundNum == 0)
{
SetPath();
PlayPlayer();
}
else
{
string currentradio = CurrentSound();
bool localcheck = isRepeat(_SelectedSound, currentradio);
if (localcheck == true)
{
PlayPlayer();
}
else
{
string Pattern = #"(music|talk)";
string selected = _Sound(currentradio, Pattern);
_SetTimer(currentradio, selected);
switch (selected)
{
case "commercial":
music_PATH = #"..\\..\\commercial\";
PlayList_byte = new List<byte>(File.ReadAllBytes(music_PATH + currentradio));
wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
wavplayer.Play();
baseTimer.Start();
break;
case "main":
talk_PATH = #"..\\..\\main\";
PlayList_byte = new List<byte>(File.ReadAllBytes(talk_PATH + currentradio));
wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
wavplayer.Play();
baseTimer.Start();
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message + ex.StackTrace + ex.Source);
}
}
private void PausePlayer()
{
MediaPlayer wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
baseTimer.Stop();
MessageBox.Show("Count: " + PlayList_byte.Count + "Pause_TIME: " + Pause_TIME + "\nPlaylist_byte" + PlayList_byte.ToString());
try
{
switch (isPaused)
{
case false:
isPaused = true;
wavplayer.Stop();
break;
case true:
isPaused = false;
string localcheck = _Sound(Pause_RADIO, #"(music|talk)");
switch (localcheck)
{
case "commercial":
music_PATH = #"..\\..\\commercial\";
wavplayer.Play(PlayList_byte.GetRange(PlayList_byte.Count - Pause_TIME, PlayList_byte.Count - Pause_TIME).ToArray());
break;
case "main":
talk_PATH = #"..\\..\\main\";
wavplayer.Play(PlayList_byte.GetRange(PlayList_byte.Count - Pause_TIME, PlayList_byte.Count - Pause_TIME).ToArray());
break;
}
break;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message + ex.Data);
}
}
private void btnPlay_Click(object sender, EventArgs e)
{
switch (isStopped)
{
case false:
isStopped = true;
btnPlay.Image = Image.FromFile(#"..\\..\\Pause.png");
lblPlay.Text = "Pause";
if (isPaused == false)
{
PlayPlayer();
}
else
{
PausePlayer();
}
break;
case true:
isStopped = false;
btnPlay.Image = Image.FromFile(#"..\\..\\Play.png");
lblPlay.Text = "Play";
PausePlayer();
break;
}
baseTimer.Elapsed += new ElapsedEventHandler(baseTimerElasped);
}
private void btnNext_Click(object sender, EventArgs e)
{
PlayPlayer();
}
private void btnStop_Click(object sender, EventArgs e)
{
MediaPlayer wavplayer = new MediaPlayer();
wavplayer.Stop();
baseTimer.Stop();
}
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnGetUpload_Click(object sender, EventArgs e)
{
Uploader FrmUpload = new Uploader();
FrmUpload.Show();
this.Hide();
}
}
class MediaPlayer
{
SoundPlayer wavplayer;
public MediaPlayer()
{
Stop();
}
public MediaPlayer(byte[] buffer)
{
MemoryStream memStream = new MemoryStream(buffer, true);
wavplayer = new SoundPlayer(memStream);
}
public void Play()
{
wavplayer.Play();
}
public void Play(byte[] buffer)
{
wavplayer.Stream.Seek(0, SeekOrigin.Begin);
wavplayer.Stream.Write(buffer, 0, buffer.Length);
wavplayer.Play();
}
public void Stop()
{
wavplayer.Stop();
}
}
Edit:
For clarity currentaudio has a file as such "music3.wav" or "talk1.wav" in it.
Super old question but just for anyone looking here's what worked for me:
double currentPos = audioplayer.CurrentPosition;
audioplayer.Play();
audioplayer.Seek(currentPos);
SoundPlayer is extremely limited, and doesn't support Pause and Resume. Are you able to use the WPF MediaElement instead? You will find it is much more powerful, supporting playing files of many types, repositioning, setting volume, pausing and resuming. You can also use it to get the file length instead of mci.

Saving to File in C#, visual studio 2010, errors

g'day guys,
i have a small error with my program where when i try to save to file an error occurs which says "A required privilege is not held by the client." I not sure how to fix this as i am running it off of my laptop which only i use and unless i have set up administrator status correctly i dont know what is going on.
I posted my code below just to be sure
Cheers.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
delegate void addlistitemcallback(string value);
public static string inputdata;
public static int MaximumSpeed, maximumRiderInput, RiderInput, Time, CurrentSpeed, DistanceTravelled, MaximumMotorOutput, MotorOutput, InputSpeed;
public static string SaveDataString;
public Thread Serial;
public static SerialPort SerialData;
public static string[] portlist = SerialPort.GetPortNames();
public static string[] SaveData = new string[4];
public static string directory = "C:\\";
public Form1()
{
Serial = new Thread(ReadData);
InitializeComponent();
int Count = 0;
for (Count = 0; Count < portlist.Length; Count++)
{
ComPortCombo.Items.Add(portlist[Count]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void StartDataButton_Click(object sender, EventArgs e)
{
SerialData = new SerialPort(ComPortCombo.Text, 19200, Parity.None, 8, StopBits.One);
SerialData.Open();
SerialData.WriteLine("P");
Serial.Start();
StartDataButton.Enabled = false;
EndDataButton.Enabled = true;
ComPortCombo.Enabled = false;
CurrentSpeed = 0;
MaximumSpeed = 0;
Time = 0;
DistanceTravelled = 0;
MotorOutput = 0;
RiderInput = 0;
SaveData[0] = "";
SaveData[1] = "";
SaveData[2] = "";
SaveData[3] = "";
SaveDataButton.Enabled = false;
if (SerialData.IsOpen)
{
ComPortStatusLabel.Text = "OPEN";
SerialData.NewLine = "/n";
SerialData.WriteLine("0");
SerialData.WriteLine("/n");
}
}
private void EndDataButton_Click(object sender, EventArgs e)
{
SerialData.Close();
SaveDataButton.Enabled = true;
//SerialData.WriteLine("1");
//SerialData.WriteLine("0");
if (!SerialData.IsOpen)
{
ComPortStatusLabel.Text = "CLOSED";
}
int i = 0;
for (i = 0; i < 4; i++)
{
if (i == 0)
{
SaveDataString = "MaximumSpeed during the Ride was = " + Convert.ToString(MaximumSpeed) + "m/h";
SaveData[i] = SaveDataString;
}
if (i == 1)
{
SaveDataString = "Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "m";
SaveData[i] = SaveDataString;
}
if (i == 2)
{
SaveDataString = "Maximum Rider Input Power = " + Convert.ToString(maximumRiderInput) + "Watts";
SaveData[i] = SaveDataString;
}
if (i == 3)
{
SaveDataString = "Maximum Motor Output Power = " + Convert.ToString(MaximumMotorOutput) + "Watts";
SaveData[i] = SaveDataString;
}
}
}
private void SaveDataButton_Click(object sender, EventArgs e)
{
//File.WriteAllBytes(directory + "image" + imageNO + ".txt", ); //saves the file to Disk
File.WriteAllLines("C:\\" + "BikeData.txt", SaveData);
}
public void updateSpeedtextbox(string value)
{
if (SpeedTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateSpeedtextbox);
Invoke(d, new object[] { value });
}
else
{
SpeedTextBox.Text = value;
}
}
public void updatePowertextbox(string value)
{
if (RiderInputTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updatePowertextbox);
Invoke(d, new object[] { value });
}
else
{
RiderInputTextBox.Text = value;
}
}
public void updateDistancetextbox(string value)
{
if (DistanceTravelledTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateDistancetextbox);
Invoke(d, new object[] { value });
}
else
{
DistanceTravelledTextBox.Text = value;
}
}
public void updateMotortextbox(string value)
{
if (MotorOutputTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateMotortextbox);
Invoke(d, new object[] { value });
}
else
{
MotorOutputTextBox.Text = value;
}
}
public void ReadData()
{
int counter = 0;
while (SerialData.IsOpen)
{
if (counter == 0)
{
try
{
InputSpeed = Convert.ToInt16(SerialData.ReadChar());
if (CurrentSpeed > MaximumSpeed)
{
MaximumSpeed = CurrentSpeed;
}
updateSpeedtextbox("Current Wheel Speed = " + Convert.ToString(InputSpeed) + "Km/h");
DistanceTravelled = DistanceTravelled + (Convert.ToInt16(InputSpeed) * Time);
updateDistancetextbox("Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "Km");
}
catch (Exception) { }
}
if (counter == 1)
{
try
{
RiderInput = Convert.ToInt16(SerialData.ReadChar());
if (RiderInput > maximumRiderInput)
{
maximumRiderInput = RiderInput;
}
updatePowertextbox("Current Rider Input Power =" + Convert.ToString(RiderInput) + "Watts");
}
catch (Exception) { }
}
if (counter == 2)
{
try
{
MotorOutput = Convert.ToInt16(SerialData.ReadChar());
if (MotorOutput > MaximumMotorOutput)
{
MaximumMotorOutput = MotorOutput;
}
updateMotortextbox("Current Motor Output = " + Convert.ToString(MotorOutput) + "Watts");
}
catch (Exception) { }
}
counter++;
if (counter == 3)
{
counter = 0;
}
}
}
private void Form1_Closed(object sender, EventArgs e)
{
if (SerialData.IsOpen)
{
SerialData.Close();
}
}
private void ComPortCombo_SelectedIndexChanged(object sender, EventArgs e)
{
StartDataButton.Enabled = true;
}
private void DistanceTravelledTextBox_TextChanged(object sender, EventArgs e)
{
}
}
}
You probably don't have write access to C:\. Try changing the save path to "C:\Users\{YouName}\Documents\BikeData.txt" instead.
Or start Visual Studio with administrative privileges by right clicking on its icon and choosing "Run as Administrator"
File.WriteAllLines("C:\" + "BikeData.txt", SaveData);
File.WriteAllLine(string,string[]), through "SecurityException" when user does not have rights to write in a particular directrory or drive so you have to give write permission, refer this link File.WriteAllLines

Categories