|
Can anyone tell me if the following can be done directly in .net without having to delve into p/invoke?
- The drive Z:\ can be mapped to C:\blah\ or c:\wibble\
- I have a load of filenames in the form C:\ paths
- I need to filter out the ones that correspond to the current Z:\ mapping (e.g. I need to ask the system where Z:\ is pointed, and string compare the filenames with the given path)
Can anyone help? (I just need the bit that tells me the location of a subst'ed drive.)
Cheers,
benjymous
|
|
|
|
|
Here you go.
ConnectionOptions conn = new ConnectionOptions();
conn.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope scope = new ManagementScope(@"\\mymachine", conn);
ObjectQuery query = new ObjectQuery("Select * From Win32_LogicalDisk Where DriveType = 4");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection coll = searcher.Get();
foreach (ManagementObject obj in coll)
{
Console.WriteLine(obj["DeviceID"].ToString());
Console.WriteLine(obj["ProviderName"].ToString());
} The ProviderName is the network drive name. DriveType=4 relates to mapped drives.
Deja View - the feeling that you've seen this post before.
|
|
|
|
|
Thanks - I'm not sure if that's doing quite what I need - it's finding mapped network drives, but not locally mapped drives
(e.g. open a cmd window and type "subst w: c:\windows" - I need to find where w: points to)
|
|
|
|
|
Here's some code I found (as opposed to wrote myself) that seems to do the trick.
using System.Runtime.InteropServices;
[DllImport("Kernel32.dll")]
internal static extern uint QueryDosDevice(string lpDeviceName,
StringBuilder lpTargetPath, uint ucchMax);
internal static string DriveIsMappedTo(string driveLetter)
{
const string MAPPED_FOLDER_INDICATOR = @"\??\";
StringBuilder volumeMap = new StringBuilder(512);
string mappedVolumeName = "";
uint mapped = QueryDosDevice(driveLetter, volumeMap, (uint)512);
if (mapped != 0)
if (volumeMap.ToString().StartsWith(MAPPED_FOLDER_INDICATOR) == true)
{
mappedVolumeName = volumeMap.ToString().Substring(4);
}
return mappedVolumeName;
}
BDF
|
|
|
|
|
Dear All
Regards!
i m going to develop a Graphics Editor in C# and OpenGL, now i am going to display my drawing on a canvas, and the canvas display area variables r
display_min_x
display_max_x
display_min_y
display_max_y
and i m going to display using the following code for zooming
------------------code------------------------
GL.GLMatrixMode(GL.GL_Projection);
GL.GLLoadIdentity();
GL.gluOrtho2D(display_min_x,display_max_x,display_min_y,display_max_y);
-------------------------------------------------------------------------
now i want that when during zooming my drawing exceeds the drawing area limits then Scrollbar becomes visible (just like in all professional applications).
so now i add scrollbar for panning, remember i am not using picturebox nor panel, simply canvas which i already has been set through coordinates system,
so plz help me to add Scrollbar in my editor.
Regards
david
|
|
|
|
|
I've wrote asynchronous http download files.So i need to test my program by try to download files within my virtual directory but some file can download completely but some can't and thrown WebException "The remote server returned an error: (403) Forbidden".I don't known what's wrong.please help
=(
this is my code
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Net;
using System.IO;
using System.Threading;
namespace DownloadAsync
{
class Program
{
const int BUFFER_SIZE = 1024;
static void Main(string[] args)
{
ArrayList Filedata = new ArrayList();
StreamReader sr = new StreamReader("filelist.txt");
string strLine = sr.ReadLine();
while (strLine != "" && strLine != null)
{
string[] data = strLine.Split(',');
Filedata.Add("http://localhost/TestFolder/" + data[1]);
Console.WriteLine("Download :- " + data[1]);
strLine = sr.ReadLine();
}
DownloadItem DItem = new DownloadItem(Filedata);
DItem.StartDownload();
Console.WriteLine("Wait...");
Console.ReadLine();
}
}
public class DownloadItem
{
private ArrayList FileList = new ArrayList();
public DownloadItem(ArrayList filelist)
{
FileList = filelist;
}
public void StartDownload()
{
for (int i = 0; i < FileList.Count; i++)
{
Thread workThread = new Thread(new ParameterizedThreadStart(DownloadMehtod));
workThread.Start((string)FileList[i]);
}
}
private void DownloadMehtod(object uri)
{
try
{
string Uri = uri as string;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Uri);
string[] ss = Uri.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string filename = ss[ss.Length - 1];
RequestState state = new RequestState();
state.request = request;
state.filename = filename;
IAsyncResult result = request.BeginGetResponse(
new AsyncCallback(RespCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private void RespCallback(IAsyncResult asynchronousResult)
{
try
{
RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
HttpWebRequest myWebRequest1 = myRequestState.request;
myRequestState.response = (HttpWebResponse)myWebRequest1.EndGetResponse(asynchronousResult);
Stream responseStream = myRequestState.response.GetResponseStream();
myRequestState.responseStream = responseStream;
int ReadCount;
byte[] buffer = new byte[4096];
FileStream f = File.Open(myRequestState.filename
, FileMode.Append
, FileAccess.Write, FileShare.None);
if (myRequestState.responseStream.CanRead)
{
while ((int)(ReadCount = myRequestState.responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
f.Write(buffer, 0, ReadCount);
}
}
f.Flush();
f.Close();
Console.WriteLine("Completed :-" + myRequestState.filename);
}
catch (WebException e)
{
Console.WriteLine("WebException raised!");
Console.WriteLine("\n{0}", e.Message);
Console.WriteLine("\n{0}", e.Status);
}
catch (Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}
}
public class RequestState
{
const int BUFFER_SIZE = 1024;
public string filename;
public StringBuilder requestData;
public byte[] bufferRead;
public HttpWebRequest request;
public HttpWebResponse response;
public Stream responseStream;
public RequestState()
{
bufferRead = new byte[BUFFER_SIZE];
requestData = new StringBuilder("");
request = null;
responseStream = null;
}
}
}
Could u help me what's wrong?
Thank =)
-- modified at 6:14 Thursday 13th September, 2007
|
|
|
|
|
Check files permissions/ownership on disk.
bug_aonz wrote: ***Sorry, I don't know how to post code with paragraph. =)
Enclose your code between <pre> and </pre> tags.
-----
If atheism is a religion, then not collecting stamps is a hobby. -- Unknown
God is the only being who, to rule, does not need to exist. -- Charles Baudelaire
|
|
|
|
|
Le Centriste wrote: Check files permissions/ownership on disk.
Yep,All of them are allowed to download.When i normally download them (without asynchronous) ,It works properly. i use the code below with multi-threading
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(TargetFilePath);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stm = resp.GetResponseStream();
int ReadCount;
byte[] buffer = new byte[65535];
FileStream f = File.Open(SaveDirectory + "/" + filename
, FileMode.Append
, FileAccess.Write, FileShare.None);
if (stm.CanRead)
{
while ((int)(ReadCount = stm.Read(buffer, 0, buffer.Length)) > 0)
{
f.Write(buffer, 0, ReadCount);
}
}
f.Flush();
f.Close();
the code above can download all my collection of files.
Is it about asynchronous method?
Have i missed something to implement AsyncCallback?
|
|
|
|
|
Maybe you are blowing off the maximum number of concurrent downloads. All threads are downloading concurrently.
This is good, except that your DownloadItem calls does not have a safe guard. Suppose someone passes an array list of thousands of files to download.
I would make an app.config file that would contain a value for the maximum of concurrent downloads, and queue the rest of the items to download.
If you allow me to point out, don't use the System.Threading.Thread class to perform a job which terminates the thread when done, like downloading a file. Consider using the BackgroundWorker[^] class or asynchronous programming using delegates[^] (BackgroundWorker would be my choice here).
The main advantage of the above is that the runtime uses a thread from a thread pool it secretly manages for you, so you don't have the overhead of starting/managing your threads.
-----
If atheism is a religion, then not collecting stamps is a hobby. -- Unknown
God is the only being who, to rule, does not need to exist. -- Charles Baudelaire
|
|
|
|
|
Thank to share your good ideas. i wil try it.
|
|
|
|
|
How to search for a file in a folder using asp.net.
|
|
|
|
|
One way is
string[] files = Directory.GetFiles("c:\\dev", "*.cs");
Deja View - the feeling that you've seen this post before.
|
|
|
|
|
Hi everyone I am trying to subtract cells in excel from a C# application.I have a for loop that fills the cells in excel. Thanks
|
|
|
|
|
To insert a formula into a cell just write the formula you want into that cell instead of assigning the cell a hardcoded value, exactly like you would using MS Excel
|
|
|
|
|
No you cant because I have a for loop and if you put that into excel its only going to sum 2 cells not the for loop but its ok I got it right.Thanks for youre answer.
|
|
|
|
|
Hi All
I am facing a strange issue and i am working on this issue for last one week,but i am not able to find it.I have a window service which reads the MSMQ .This windows service will do only this function.Now, when some thing is written to MSMQ, window service will read the msmq.Now there is nothing in queue ,then also it will loop and if some thing comes inside the msmq then again it will read ...this works fine if i am doing in regular intervals.
Now if am not doing any operations for two or three hours ,then status of windows service will be started but it will not reading the msmq,and it is not throwing any error..also...this is the strange thing i am facing..why it is behaving like this.Can any one help me in this idea.I am pasting the start section of of mywindows service here .can any one tell me what is wrong in this code.Thanks in advance
this code i am calling inside a thread..
try
{
MessageQueue mq = null;
System.Messaging.Message msg = null;
while(true)
{
//MessageQueue mq = null;
//System.Messaging.Message msg = null;
try
{
if(mq == null)
{
mq = new System.Messaging.MessageQueue (XMLReprocessMSMQPath);
}
RemoteLoggingManager.LogMessage(LoggingMessageTypes.Error, APPLICATIONNAME,"Read Queue", LoggingMessageTargets.Both);
msg = mq.Receive(new TimeSpan(0,0,0,10,0));
RemoteLoggingManager.LogMessage(LoggingMessageTypes.Error, APPLICATIONNAME,"Data Rec", LoggingMessageTargets.Both);
msg.Formatter = new ActiveXMessageFormatter();
XMLReprocessMSMQFileName=ReceiveMessage(msg.Body.ToString());
SendXMLToWebervice(XMLReprocessMSMQFileName);
}
catch (System.Messaging.MessageQueueException ex)
{
if(ex.ErrorCode != -2147467259) // Ignore timeout error
{
RemoteLoggingManager.LogMessage(LoggingMessageTypes.Error, APPLICATIONNAME,ex.ToString(), LoggingMessageTargets.Both);
mq.Close();
mq.Dispose();
mq = null;
MessageQueue.ClearConnectionCache();
Thread.Sleep(10000);
}
else
{
mq = null;
}
}
catch (Exception ex)
{
RemoteLoggingManager.LogMessage(LoggingMessageTypes.Error, APPLICATIONNAME,ex.ToString(), LoggingMessageTargets.Both);
mq.Close();
mq.Dispose();
mq = null;
MessageQueue.ClearConnectionCache();
}
}
}
catch(Exception ex)
{
RemoteLoggingManager.LogMessage(LoggingMessageTypes.Information , APPLICATIONNAME,
"Reprocess MSMQ Catch block :" + DateTime.Now.ToLongTimeString(), LoggingMessageTargets.Both);
}
finally
{
RemoteLoggingManager.LogMessage(LoggingMessageTypes.Information , APPLICATIONNAME,"Finally block executed " +
DateTime.Now.ToLongTimeString(), LoggingMessageTargets.Both);
}
Regards
DilipRam
|
|
|
|
|
Hi guys.
I have, after alot of hard work, finally got this to work - well.... almost
I have a remoting server using TCPChannel. And i got some clients connecting to this server. When i from the beginning connects 3 client, all works fine, when someone connects, the server sends events to each client that they should update their list of clients. But when one of them Disconnects with this code:
if (SignedIn)<br />
{<br />
server.SignOut(MyUniqueID);
ChannelServices.UnregisterChannel(Channel);<br />
}
And then siqns in again, he's not getting the event when someone connects or disconnects, but the other clients does, even when the failing client connects/disconnects. BUT if i close this one client that fails, and open it up again, it all work just fine again, very strange.
I got a very simple and clean example code if anyone wants to help me
BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider();<br />
serverProv.TypeFilterLevel = TypeFilterLevel.Full;<br />
<br />
IDictionary props = new Hashtable();<br />
props["name"] = "ServerChannel";<br />
props["port"] = 666;<br />
<br />
<br />
TcpChannel Channel = new TcpChannel(props, null, serverProv);<br />
ChannelServices.RegisterChannel(Channel, false);<br />
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Server), "Server", WellKnownObjectMode.Singleton);<br />
<br />
Console.WriteLine("Server is running...");
inaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider();<br />
serverProv.TypeFilterLevel = TypeFilterLevel.Full;<br />
IDictionary props = new Hashtable();<br />
props["port"] = 0;<br />
<br />
CallbackSink.OnHostToClient += new ClientEvent(OnHostToClient);<br />
<br />
Channel = new TcpChannel(props, null, serverProv);<br />
ChannelServices.RegisterChannel(Channel, false);<br />
server = (Server)Activator.GetObject(typeof(Server), "tcp://127.0.0.1:666/Server");
|
|
|
|
|
|
|
Hello,
can anyone illustrate a step by step procedure for using resource manager or some equvalent in C#.
I am not able to embed the main assembly resource file, .resources, in
the executable assembly.So please guide me in creating and embedding resource files as well.
Keshav Kamat
India
|
|
|
|
|
Look around on this site, there are some articles on embedding resources into assemblies.
"Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon
|
|
|
|
|
Some of the functionalities can't write in .net easily, where as possible in C, C++, VC++. So how to use those libraries in .NET (C#).
|
|
|
|
|
|
Hi,
I have created a DLL in dotnet and it accepts one parameter i.e string.
When i call the method of the dll it throws me following error:
Error Type:
Microsoft VBScript runtime (0x800A01C2)
Wrong number of arguments or invalid property assignment: 'display'
/project/usedll.asp, line 46
Please suggest.
Pavas
|
|
|
|
|
How are you calling the method in that dll ?
Thanks and Regards
Sandeep
If If you look at what you do not have in life, you don't have anything,
If you look at what you have in life, you have everything... "
|
|
|
|
|