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 8 years ago.
Improve this question
I am doing recording in my application using C#.
I record voice to the same file and play it but the SoundPlayer plays the contents recorded first time.
For example I have file test.wav where I record "hello" and then I record "hi" to the same file
by overwriting the file. When I play the file test.wav player plays "hello".
I have only one instance of player, e.g.
public static System.Media.SoundPlayer Player;
static void Main()
{
try
{
Player = new System.Media.SoundPlayer();
}
catch (Exception ex)
{
}
}
Code for playing the file:
public static void Play(string fileName)
{
if (File.Exists(fileName))
{
Program.Player.SoundLocation = fileName;
Program.Player.Load();
if (Program.Player.IsLoadCompleted)
{
Program.Player.Play();
}
}
}
I don't know what is wrong here.
Inside the Setter for the SoundLocation property is an interesting check:
set
{
if (value == null)
{
value = string.Empty;
}
if (!this.soundLocation.Equals(value))
{
this.SetupSoundLocation(value);
this.OnSoundLocationChanged(EventArgs.Empty);
}
}
You can see that it looks to see if the new location differs from the old one. If it does, then it does some setup work. If it doesn't, it essentially does nothing.
I'm betting you can get around this by doing something like this:
public static void Play(string fileName)
{
if (File.Exists(fileName))
{
Program.Player.SoundLocation = "";
Program.Player.SoundLocation = fileName;
Program.Player.Load();
if (Program.Player.IsLoadCompleted)
{
Program.Player.Play();
}
}
}
The first call to the SoundLocation setter would clear out the loaded stream. The second one would then set it up properly with the location again and allow for Load to load the stream as expected.
Related
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 2 years ago.
Improve this question
My app is a 32 bit .Net VS 2017 app. File.Exists always returns false in my app. Either running in VS, deployed locally, or as admin. Running on a Windows 10 64 bit system. Paths are good because the File.Copy works (but always since File.Exist isn't working. I don't want File.Copy to run unless file doesn't exist. Maybe suggestions for a workaround if I can't get it to work? File permissions shouldn't be a problem since the file is in the Documents folder. Maybe a better SpecialFolder to use than MyDocuments? Any help would be appreciated. Thanks in advance. Code below.
// Class variables
public static string appPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
"\\Lottery Analyzer Expert International";
public static string dbPath = appPath + "\\database\\";
public static string dbFile = "Histories.sqlite";
// Class method
public void copyInputFiles_db()
{
string dest = dbPath + dbFile;
string src = Application.StartupPath + "\\database\\" + dbFile;
if (!File.Exists(dest)) { }
{
File.Copy(src, dest, true); // if input files not found in appPath copy from install folder
bool do_download = true;
DialogResult dialogResult2 = MessageBox.Show(
"The history database was copied from the application's startup to it's working dirctory. This happens when first running " +
"the application or the history file is missing. Would you like to update that file from the web?",
"Download file?", MessageBoxButtons.YesNo);
if (dialogResult2 == DialogResult.Yes)
{
do_download = true;
}
else if (dialogResult2 == DialogResult.No)
{
do_download = false;
}
if (do_download)
downloadAllTheHistoryFIles_db();
}
printTextFiles();
}
You know that the code below the if is always executed?
if (!File.Exists(dest)) { } // << the { } is the IF scope
{ // <- this is a new scope also, but not part of the if..
File.Copy(src, dest, true);
bool do_download = true;
// *SNIP*
}
Remove the { } behind the if
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 3 years ago.
Improve this question
I am generating permutations from algorithm and writing same to a text file.,after generating it gives no error but only one permutations is found in the text file.is it encoding problem or something else i am missing.
'''
private void button2_Click(object sender, EventArgs e)
{
string str33 = textBox1.Text;
char[] arr = str33.ToCharArray();
int r = Convert.ToInt32(textBox3.Text);
int n = arr.Length;
printCombination(arr, n, r);
}
'''
The line which finally writes to the text file goes like this.
'''
File.WriteAllText(finalocation, str);
'''
where finalocation is the path of the text file and str is the string to be written to it.Anything more required i will reply further.
Store your all permutations in a list and send the list to your designed method to write in file.
The method for writing should be similar to the following.
public void printToFile(List<string> allPermutations) {
using (StreamWriter sw = new StreamWriter("names.txt")){
foreach (string s in allPermutations){
sw.WriteLine(s);
}
}
}
I have an app that reads from text files to determine which reports should be generated. It works as it should most of the time, but once in awhile, the program deletes one of the text files it reads from/writes to. Then an exception is thrown ("Could not find file") and progress ceases.
Here is some pertinent code.
First, reading from the file:
List<String> delPerfRecords = ReadFileContents(DelPerfFile);
. . .
private static List<String> ReadFileContents(string fileName)
{
List<String> fileContents = new List<string>();
try
{
fileContents = File.ReadAllLines(fileName).ToList();
}
catch (Exception ex)
{
RoboReporterConstsAndUtils.HandleException(ex);
}
return fileContents;
}
Then, writing to the file -- it marks the record/line in that file as having been processed, so that the same report is not re-generated the next time the file is examined:
MarkAsProcessed(DelPerfFile, qrRecord);
. . .
private static void MarkAsProcessed(string fileToUpdate, string
qrRecord)
{
try
{
var fileContents = File.ReadAllLines(fileToUpdate).ToList();
for (int i = 0; i < fileContents.Count; i++)
{
if (fileContents[i] == qrRecord)
{
fileContents[i] = string.Format("{0}{1} {2}"
qrRecord, RoboReporterConstsAndUtils.COMPLETED_FLAG, DateTime.Now);
}
}
// Will this automatically overwrite the existing?
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
}
catch (Exception ex)
{
RoboReporterConstsAndUtils.HandleException(ex);
}
}
So I do delete the file, but immediately replace it:
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
The files being read have contents such as this:
Opas,20170110,20161127,20161231-COMPLETED 1/10/2017 12:33:27 AM
Opas,20170209,20170101,20170128-COMPLETED 2/9/2017 11:26:04 AM
Opas,20170309,20170129,20170225-COMPLETED
Opas,20170409,20170226,20170401
If "-COMPLETED" appears at the end of the record/row/line, it is ignored - will not be processed.
Also, if the second element (at index 1) is a date in the future, it will not be processed (yet).
So, for these examples shown above, the first three have already been done, and will be subsequently ignored. The fourth one will not be acted on until on or after April 9th, 2017 (at which time the data within the data range of the last two dates will be retrieved).
Why is the file sometimes deleted? What can I do to prevent it from ever happening?
If helpful, in more context, the logic is like so:
internal static string GenerateAndSaveDelPerfReports()
{
string allUnitsProcessed = String.Empty;
bool success = false;
try
{
List<String> delPerfRecords = ReadFileContents(DelPerfFile);
List<QueuedReports> qrList = new List<QueuedReports>();
foreach (string qrRecord in delPerfRecords)
{
var qr = ConvertCRVRecordToQueuedReport(qrRecord);
// Rows that have already been processed return null
if (null == qr) continue;
// If the report has not yet been run, and it is due, add i
to the list
if (qr.DateToGenerate <= DateTime.Today)
{
var unit = qr.Unit;
qrList.Add(qr);
MarkAsProcessed(DelPerfFile, qrRecord);
if (String.IsNullOrWhiteSpace(allUnitsProcessed))
{
allUnitsProcessed = unit;
}
else if (!allUnitsProcessed.Contains(unit))
{
allUnitsProcessed = allUnitsProcessed + " and "
unit;
}
}
}
foreach (QueuedReports qrs in qrList)
{
GenerateAndSaveDelPerfReport(qrs);
success = true;
}
}
catch
{
success = false;
}
if (success)
{
return String.Format("Delivery Performance report[s] generate
for {0} by RoboReporter2017", allUnitsProcessed);
}
return String.Empty;
}
How can I ironclad this code to prevent the files from being periodically trashed?
UPDATE
I can't really test this, because the problem occurs so infrequently, but I wonder if adding a "pause" between the File.Delete() and the File.WriteAllLines() would solve the problem?
UPDATE 2
I'm not absolutely sure what the answer to my question is, so I won't add this as an answer, but my guess is that the File.Delete() and File.WriteAllLines() were occurring too close together and so the delete was sometimes occurring on both the old and the new copy of the file.
If so, a pause between the two calls may have solved the problem 99.42% of the time, but from what I found here, it seems the File.Delete() is redundant/superfluous anyway, and so I tested with the File.Delete() commented out, and it worked fine; so, I'm just doing without that occasionally problematic call now. I expect that to solve the issue.
// Will this automatically overwrite the existing?
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
I would simply add an extra parameter to WriteAllLines() (which could default to false) to tell the function to open the file in overwrite mode, and not call File.Delete() at all then.
Do you currently check the return value of the file open?
Update: ok, it looks like WriteAllLines() is a .Net Framework function and therefore cannot be changed, so I deleted this answer. However now this shows up in the comments, as a proposed solution on another forum:
"just use something like File.WriteAllText where if the file exists,
the data is just overwritten, if the file does not exist it will be
created."
And this was exactly what I meant (while thinking WriteAllLines() was a user defined function), because I've had similar problems in the past.
So, a solution like that could solve some tricky problems (instead of deleting/fast reopening, just overwriting the file) - also less work for the OS, and possibly less file/disk fragmentation.
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 6 years ago.
Improve this question
I have around 5000 files located in FTP, so i am downloading those by using FTP and then unzipping the files, finally processing and pushing in to oracle database.Except processing and pushing in to database everything going fine, i dont know why processing is not happeneing .I can see debugger hitting that method but it is not going in to inside method.How to fix this issue?
var list = ftp.GetFileList(remotepath);
//-------------------
DateTime dt = DateTime.Now;
string st = String.Format("{0:yyyyMMdd}", dt);//20161120
Task[] myTasks = new Task[list.Count];
int i = 0;
foreach (string item in list)
{
{
if (item.StartsWith("GExport_") && (!item.ToUpper().Contains("DUM")) && (item.Contains(st)) && (!item.ToUpper().Contains("BLK")))
{
4gpath = item;
//Downloadfile()
ftp.Get(dtr["REMOTE_FILE_PATH"].ToString() + 4gpath , #localDestnDir + "\\" + dtr["SOURCE_PATH"].ToString());
download_location_hw = dtr["LOCAL_FILE_PATH"].ToString();
// Spin off a background task to process the file we just downloaded
myTasks[i++] = Task.Factory.StartNew(() =>
{
//Extractfile()
ExtractZipfiles(download_location_hw + "//" + huwawei4gpath, dtr["REMOTE_FILE_PATH"].ToString(),
dtr["FTP_SERVER"].ToString(), dtr["FTP_USER_ID"].ToString(),
dtr["TECH_CODE"].ToString(), dtr["VENDOR_CODE"].ToString());
//Extract the zip file referred to by download_location_hw
// Process the extracted zip file
ProcessFile()
});
}
}
}
Task.WaitAll(myTasks);
Here ProcessFile() method is not executing at all
EDIT
there was typo in filepath cause issue,thanks,but my question is is there any synchronization issue,since first unzip the file and same time process file where file was not available,will it wait for unzipping before processing –
added check while(!File.Exists("")) { Thread.Sleep(1000);
does that make any isssues??
If you try this code here, you will notice it works. It is very similar to your code. Since this works, your issue is elsewhere and not related to Task(s).
class Program {
static void Main(string[] args) {
var list = new List<string> { "1", "2" };
Task[] myTasks = new Task[ list.Count ];
int i = 0;
foreach( string item in list ) {
// Spin off a background task to process the file we just downloaded
myTasks[ i++ ] = Task.Factory.StartNew( () =>
{
//Extract the zip file referred to by download_location_hw
// Process the extracted zip file
ProcessFile();
} );
}
Task.WaitAll( myTasks );
Console.WriteLine( "in main after processing..." );
Console.Read();
}
private static void ProcessFile() {
Console.Write( "Processed..." );
}
}
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 9 years ago.
Improve this question
here is my code:
public static bool createFile(string dir) {
dir="c:\\e.bat";
System.IO.File.Create(dir);
if (System.IO.File.Exists(dir))
{
try
{
StreamWriter SW;
SW = System.IO.File.CreateText(dir);
SW.WriteLine("something ");
SW.Close();
}
catch (Exception e)
{
Console.Write(e.Message);
Console.ReadLine();
return false;
}
}
return true;
}
here dir is the current directory. i am facing the error The process cannot access the file because it is being used by another process.how can i solve this problem?
You're calling File.Create at the start of the method - which is returning you a stream, which stays open. It's not clear why you're calling that at all, but I'd suggest just removing that line.
You should also use a using statement, only catch specific exceptions, use appropriate using directives, and follow .NET naming conventions. For example:
using System.IO;
...
public static bool CreateFile(string file)
{
using (var writer = File.CreateText(file))
{
try
{
writer.WriteLine("something ");
}
catch (IOException e)
{
// TODO: Change the handling of this. It's weird at the moment
Console.Write(e.Message);
Console.ReadLine();
return false;
}
}
return true;
}
I've removed the check for the file existing, as with the previous code it would always exist because you'd just created it.
You should also consider using File.WriteAllText as a simpler way of writing the file.