Error when reading audio file? - c#

I have the following function that I am attempting to use to determine the length of an MP3 file:
public static string GetMP3DurationBackup(string Filename)
{
string Duration = null;
WMPLib.WindowsMediaPlayer w = new WMPLib.WindowsMediaPlayer();
WMPLib.IWMPMedia m = w.newMedia(Filename);
if (m != null)
{
Duration = m.durationString;
}
w.close();
return Duration;
}
I have run into an issue where I get the following error:
Retrieving the COM class factory for component with CLSID
{6BF52A52-394A-11D3-B153-00C04F79FAA6} failed due to the following
error: 80040154..
when I call the above function from my web application (call below):
string test = MediaUtil.GetMP3DurationBackup(#"C:\Temp\Audio\bad.mp3");
But when I call it from a console application test harness I created (exact same call as above) it works fine. I have set the project that contains the function to target x86 in the Build properties, but that did not fix the issue.
Does anyone know why this would happen? Suggestions on where to start to debug this?
UPDATED FOR BOUNTY:
Ok, I've tried a number of things but I am still getting this error. Among other things I have tried the steps below which I felt were the most promising, but no dice:
Went into my registry and confirmed that the value at:
HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{6BF52A52-394A-11d3-B153-00C04F79FAA6}\InprocServer32
is refering to C:\WINDOWS\SysWOW64\wmp.dll
Opened command prompt,
navigated to C:\WINDOWS\SysWow64, ran: regsvr32.exe wmp.dll
I have created a console app test harness and I am able to reproduce the error if I run the test project in x64. If I switch it to x86 it works fine.
Does anyone have any idea of why the above would not resolve the issue? Suggestions on where to look next?

You say it doesn't work in x64, but you try to register the 32-bit version of wmp.dll (C:\Windows\SysWow64 contains 32-bit assemblies).
Try to register the x64 version of wmp.dll, which is located in C:\Windows\System32 on a 64-bit platform.
If you don't have this file then there probably is no 64bit Windows Media Player available for your platform. But there is a workaround:
Create a 32-bit console application that takes the mp3 filename as command line argument and outputs the duration to stdout using Console.WriteLine, then in the webapp, you call the console application and capture the output like in this example on MSDN

Give this lib a whirl. Its fast and has no special requirements for software to be installed on the machine.
http://naudio.codeplex.com/

Related

Calling another EXE with C# on Windows fails on target machine

I have created a Windows shell extension that provides a menu to users when they right-click in File Explorer. This then invokes a small dialogue App.
I'm a novice at software development so there is probably some schoolboy error I'm making but I just can't see it.
For testing purposes I am hard-coding the path to the EXE and ensuring it's present on the VM.
private void CallExteralAddLocation(string sFullPath)
{
string sEXE = Path.Combine(Application.StartupPath, "AddLocation.exe");
WriteLog(sEXE);
// during testing, hard-code this path
sEXE = "C:\\temp\\AddLocation.exe";
System.Diagnostics.Process.Start(sEXE, sFullPath);
}
private void WriteLog(string sText)
{
using (StreamWriter sr = new StreamWriter("C:\\Temp\\ShellExtLog.txt"))
{
sr.WriteLine(sText);
}
}
It works fine on my host machine but when running on a VM running Windows 10, which is where I am testing it, the dialogue App does not get invoked.
I have checked that I can invoke the AddLocation.exe from a command window on the VM and that works as expected. So it looks like it's just not getting called.
As it's a shell extension it's very difficult to debug. I tried using MessageBoxes and writing to the console but those wouldn't work, so I have added the WriteLog so that I have some idea of what it's doing.
This works on the host machine i.e. a log file is created and it shows the path to the EXE, but no log file is created on the VM.
NOTE: When testing on either machine, I'm installing afresh from the application's MSI. Also note that the host is running Windows 11 and the VM is running Windows 10.
So, why does the same code fail to either run the EXE or create a log file on the VM?
I eventually worked out that the problem was how C# handles strings.
If you read through my problem above you will see that, weirdly the same code worked fine on Windows 11 but not on Windows 10.
The problem was that I was letting the compiler interpret the path string. I had 'escaped' the slashes as shown here and it should have worked fine:
sEXE = "C:\\temp\\AddLocation.exe";
Changing it to the following resolved the problem so that it works on both now:
sEXE = #"C:\temp\AddLocation.exe";
Similarly, whereas it wouldn't create a log file on Win10, changing the path to the log file to the following fixed it:
using (StreamWriter sr = new StreamWriter(#"C:\Temp\ShellExtLog.txt"))

C# Class Library throws FileNotFoundException while trying to load another library

I try to connect to a fiscal device with a C#.
I use this documentation to do so: http://integration.atol.ru/api-en/#connection-to-project
So basically I have a driver of the device installed on my PC (fprt10.dll) and there is a "wrapper" assembly that allows me to work with this driver from C# (Atol.Drivers10.Fptr.dll). I import this wrapper into my project as a reference.
I have the following constructor in my class:
public MyClass()
{
IFptr fiscalPrinter = new Fptr();
// Here comes several settings to configure connection
fiscalPrinter.applySingleSettings();
fiscalPrinter.open();
fiscalPrinter.beep();
fiscalPrinter.close();
}
To test the solution I use another application, that loads my Class Library as a dependency.
When I call a constructor of MyClass I get an exception:
System.IO.FileNotFoundException: Driver not installed
at Atol.Drivers10.Fptr.Fptr.loadDriver(String path)
at Atol.Drivers10.Fptr.Fptr..ctor()
at MySolution.MyClass.MyClass()
...
If I create instance of Fptr with a path to the driver
IFptr fiscalPrinter = new Fptr(#"C:\path\fptr10.dll")
I get the slightly different exception, but I believe the problem is the same:
System.IO.FileNotFoundException: Can`t load driver library "C:\path\fptr10.dll"
at Atol.Drivers10.Fptr.Fptr.raiseNotFoundError(String path, Exception reason)
at Atol.Drivers10.Fptr.Fptr.loadDriver(String path)
at Atol.Drivers10.Fptr.Fptr..ctor(String libraryPath)
at MySolution.MyClass.MyClass()
...
But when I create a Console Application and put in there exact same code (both versions with path and without), everything works: the device beeps, there are no exceptions.
What could be the reason for that behavior and how to fix this?
The issue may be one of the following
The test application is using 'target platform' different than the console application which works fine. The device driver folders expected for each platform could be different. e.g. Changing the targeted platform from 'any CPU' to 'x64' / 'x86' (depending on the type of OS where you are running it) will help
Try running the test application from admin command prompt. Permissions issue may reflect as 'file not found' (instead of 'file could not be loaded').
Use an assembly binding viewer tool to debug the issue further
Refer to Could not load file or assembly or one of its dependencies for more discussion and inputs on the assembly loading issues.
Thank you samiksc.
The issue was in the test app. The driver and OS that I use are both x64, but the test application is x86. With x86 driver everything works.

C# .Net Service won't install on Win 7 64 bit

.Net 3.5
I've built into the service exe the ability for it to install itself using a -i feature. I have a custom installer class and am using a common technique on found online here. That installer class basically has it's own service and serviced process installer.
This code has worked well for a very long time. Finally ran into a Win 7 64 bit machine were it refuses to install.
Basically, the log shows it's installing the service and that succeeds. Then it tries to create an event log and that fails with
An exception occurred during the Install phase.
System.ComponentModel.Win32Exception: The specified service already
exists
I just got done having the OS completely reinstalled from scratch, first thing I did was try to install as a service, and it's the same error. Why is it thinking that event log is already there?
I've already read all the other posts and I've browsed my registry and there is nothing in there for my service or event log. I have full admin rights, when I try to open cmd as administrator, it doesn't even prompt me, so as far as I can tell, I am an admin (I can see that in my user profile).
I even added code to check to see if it found the EventLog using System.Diagnostics.EventLog.SourceExists which does report it found it, and so I added a call to System.Diagnostics.EventLog.DeleteEventSource but that doesn't help.
I even tried removing the EventLog installer from the ServiceInstaller, but then it starts failing for other reasons.
Any ideas?
Here is some sample code for an alternate installer I tried that I found here with the same results:
public partial class Service1Installer : Installer
{
public Service1Installer()
{
InitializeComponent();
ServiceProcessInstaller process = new ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
ServiceInstaller serviceAdmin = new ServiceInstaller();
serviceAdmin.StartType = ServiceStartMode.Manual;
serviceAdmin.ServiceName = "Service1";
serviceAdmin.DisplayName = "Service1";
serviceAdmin.Description = "Service1";
Installers.Add(serviceAdmin);
Installers.Add(process );
}
}
uninstall your service
installutil /u yourproject.exe
restart your machine
http://msdn.microsoft.com/en-us/library/sd8zc8ha(v=vs.80).aspx
let me know if you still have a issue
Use installutil as #MicahArmantrout mentions, if the exe still resides on disk.
Otherwise, open a commandline as Administrator and execute: sc delete "my service name"
In the end, my problem was our internal installer. I commented it out and now just install the service from the command line and it now installs on 64 bit OS. Still don't know why it would work before on 32 bit.

File exists in Windows Explorer and notepad, but is not accessable in my program

Why does the following problem happen?
Scenario:
Make sure that IIS is installed
Execute "notepad
%WINDIR%\System32\inetsrv\config\applicationHost.config" using admin
account
Actual Result: the file is successfully opened in notepad
Execute the following code in admin account's context:
string filePath = #"%WINDIR%\System32\inetsrv\config\applicationHost.config";
Console.WriteLine(File.Exists(Environment.ExpandEnvironmentVariables(filePath)));
Actual Result: False
Expected Result: True
The problem is if you are running a 32-bit application on a 64-bit OS, the .Net framework automatically redirects the request from %WINDIR%\System32 to %WINDIR%\SysWOW64.
If you change your project to target 64-bit, this will solve your problem.
You can also resolve the problem by changing System32 to sysnative, but only if you leave the application as a 32-bit app:
string filePath = #"%WINDIR%\sysnative\inetsrv\config\applicationHost.config";
This might be due to file system redirection. AFAIK t happens either for 32/64 bit mismatch or in case of low-privilege (UAC) processes.
I know of now way of disabling that behavior using managed APIs. You need to use http://msdn.microsoft.com/en-us/library/windows/desktop/aa365743(v=vs.85).aspx and/or be a high privilege process.
If you change your project to target 64-bit, this is likely to solve your problem.
I can't reproduce your result. When I run this from an administrator command line prompt, I get exists = True.
string s = #"%WINDIR%/System32\inetsrv\config\applicationHost.config";
bool exists = File.Exists(Environment.ExpandEnvironmentVariables(s));
Console.WriteLine("exists = {0}", exists);
I'm running Windows Server 2008, 64-bit. .NET 4.0.

Process.Start("IIS Manager.lnk") fails with "The system cannot find the file specified"

I'm launching the path C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools\IIS Manager.lnk via Process.Start, but it fails with The system cannot find the file specified.
The link shows up on a dir, so it exists.
Can it be permissions?
Notes:
The path is auto-discovered by iterating over the Start Menu directory.
I can launch it via explorer and command line.
Clarifications:
Code is as follows:
public void Execute() { Process.Start(_shortcut.FullName);}
_shortcut is of type FileInfo
_shortcut.Exists is true, so the file can be found
replacing _shortcut.FullName with the explicit path #"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools\IIS Manager.lnk" has the same effect.
This is a WPF app using Caliburn and MEF.
Running as Administrator has the same effect.
This here on the other hand seems to work:
[Fact]
public void TestIisManager()
{
var path = new FileInfo(#"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools\IIS Manager.lnk");
Process.Start(path.FullName);
}
It does seem to be a bit "environment" based.
Second clarification:
It seems to work in a Windows 7 x86 but not in a Windows 7 x64.
I ran into this recently. Windows Forms based solution, VS2013, x64 machine. Process.Start() could not launch applications via .lnk file. Using process explorer, it seemed that the target specified in the .lnk file was resolving incorrectly to c:\program files (x86)... instead of c:\program files... I followed Bruno's excellent advice, but then again my Target was already marked as "AnyCPU".
After some head scratching, it turned out there's a new compiler flag in VS11+ called "Prefer 32-bit" that was checked by default. This was forcing the EXE output to be 32-bit even though my OS was 64-bit and platform was set to AnyCPU. After I unchecked and recompiled, the problem was fixed.
More reading at: http://blogs.microsoft.co.il/sasha/2012/04/04/what-anycpu-really-means-as-of-net-45-and-visual-studio-11/
Found the issue.
The WPF application was compiled as x86 (all other dlls were compiled as AnyCPU), and when launching some executables or links in a 64 bit machine it failed.
Changing the "Platform Target" to AnyCPU fixes this.
This may not actually relate to your situation, but you can launch the IIS Manager by using
Process.Start("inetmgr.exe")
If you want to continue to use the shortcut, it will probably work if you start the process using a ProcessStartInfo and set ProcessStartInfo.UseShellExecute to true
Can you make sure that you are trying this from an STA thread? You can see whether the apartment state is a problem if the following sample succeeds:
using System;
using System.Diagnostics;
public class Program
{
// make sure to call Process.Start from an STA thread
[STAThread]
static void Main(string[] args)
{
Process.Start(#"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools\IIS Manager.lnk");
}
}
Process.Start calls ShellExecute under the hood to run the file passed. As described by Raymond Chen, shell functions require an STA thread:
One possible reason why ShellExecute returns SE_ERR_ACCESSDENIED and ShellExecuteEx returns ERROR_ACCESS_DENIED
As stated already, you will see the "The system cannot find the file specified" error because Windows is looking for inetmgr.exe in ...\SysWOW64\intsrv\ (caused by file system redirection), but it only exists in ...\System32\intsrv\.
This is caused by your 32-bit executable attempting to launch a 64-bit executable. As suggested, not using a 32-bit executable will solve this, but for anyone who must build for 32-bit (a WiX installer bundle in my case), try the following.
Using the start menu LNK/shortcut to inetmgr.exe instead of the executable is a good start, but an extra level of distance is required. This can be provided by using explorer.exe, which can be launched from a 32-bit executable:
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "explorer.exe";
startInfo.Arguments = "/seperate /root,\"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Administrative Tools\\IIS Manager.lnk\"";
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo = startInfo;
process.Start();
It's a bit of a hack, but try launching it like this:
string path = #"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools\IIS Manager.lnk";
Process.Start("cmd.exe", String.Format("/k \"\"{0}\"\"",path));
Note the double quotes needed to save the spaces in the path.
That way, you might see a more precise error message and/or walk around in the command environment afterwards to see what is wrong with the path.

Categories

Resources