Search Results

Search found 81 results on 4 pages for 'directoryinfo'.

Page 2/4 | < Previous Page | 1 2 3 4  | Next Page >

  • MEF + Plug-In not updating

    - by mybrokengnome
    I asked this on the MEF Codeplex forum already, but I haven't gotten a response yet, so I figured I'd try StackOverflow. Here's the original post if anyone's interested (this is just a copy from it): MEF Codeplex "Let me first say that I'm completely new to MEF (just discovered it today) and am very happy with it so far. However, I've ran in to a problem that is very frustrating. I'm creating an app that will have a plugin architecture and the plugins will only be stored in a single DLL file (or coded into the main app). The DLL file needs to be able to be recompiled during run-time and the app should recognize this and re-load the plugins (I know this is difficult, but it's a requirement). To accomplish this I took the approach covered http://blog.maartenballiauw.be/category/MEF.aspx there (look for WebServerDirectoryCatalog). Basically the idea is to "monitor the plugins folder, copy the new/modified assemblies to the web application’s /bin folder and instruct MEF to load its exports from there." This is my code, which is probably not the correct way to do it but it's what I found in some samples around the net: main()... string myExecName = Assembly.GetExecutingAssembly().Location; string myPath = System.IO.Path.GetDirectoryName(myExecName); catalog = new AggregateCatalog(); pluginCatalog = new MyDirectoryCatalog(myPath + @"/Plugins"); catalog.Catalogs.Add(pluginCatalog); exportContainer = new CompositionContainer(catalog); CompositionBatch compBatch = new CompositionBatch(); compBatch.AddPart(this); compBatch.AddPart(catalog); exportContainer.Compose(compBatch); and private FileSystemWatcher fileSystemWatcher; public DirectoryCatalog directoryCatalog; private string path; private string extension; public MyDirectoryCatalog(string path) { Initialize(path, "*.dll", "*.dll"); } private void Initialize(string path, string extension, string modulePattern) { this.path = path; this.extension = extension; fileSystemWatcher = new FileSystemWatcher(path, modulePattern); fileSystemWatcher.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed); fileSystemWatcher.Created += new FileSystemEventHandler(fileSystemWatcher_Created); fileSystemWatcher.Deleted += new FileSystemEventHandler(fileSystemWatcher_Deleted); fileSystemWatcher.Renamed += new RenamedEventHandler(fileSystemWatcher_Renamed); fileSystemWatcher.IncludeSubdirectories = false; fileSystemWatcher.EnableRaisingEvents = true; Refresh(); } void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e) { RemoveFromBin(e.OldName); Refresh(); } void fileSystemWatcher_Deleted(object sender, FileSystemEventArgs e) { RemoveFromBin(e.Name); Refresh(); } void fileSystemWatcher_Created(object sender, FileSystemEventArgs e) { Refresh(); } void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e) { Refresh(); } private void Refresh() { // Determine /bin path string binPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"); string newPath = ""; // Copy files to /bin foreach (string file in Directory.GetFiles(path, extension, SearchOption.TopDirectoryOnly)) { try { DirectoryInfo dInfo = new DirectoryInfo(binPath); DirectoryInfo[] dirs = dInfo.GetDirectories(); int count = dirs.Count() + 1; newPath = binPath + "/" + count; DirectoryInfo dInfo2 = new DirectoryInfo(newPath); if (!dInfo2.Exists) dInfo2.Create(); File.Copy(file, System.IO.Path.Combine(newPath, System.IO.Path.GetFileName(file)), true); } catch { // Not that big deal... Blog readers will probably kill me for this bit of code :-) } } // Create new directory catalog directoryCatalog = new DirectoryCatalog(newPath, extension); directoryCatalog.Refresh(); } public override IQueryable<ComposablePartDefinition> Parts { get { return directoryCatalog.Parts; } } private void RemoveFromBin(string name) { string binPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ""); File.Delete(Path.Combine(binPath, name)); } So all this actually works, and after the end of the code in main my IEnumerable variable is actually filled with all the plugins in the DLL (which if you follow the code is located in Plugins/1 so that I can modify the dll in the plugins folder). So now at this point I should be able to re-compile the plugins DLL, drop it in to the Plugins folder, my FileWatcher detect that it's changed, and then copy it into folder "2" and directoryCatalog should point to the new folder. All this actually works! The problem is, even though it seems like every thing is pointed to the right place, my IEnumerable variable is never updated with the new plugins. So close, but yet so far! Any suggestions? I know the downsides of doing it this way, that no dll is actually getting unloaded and causing a memory leak, but it's a Windows App and will probably be started at least once a day, and the plugins are un-likely to change that often, but it's still a requirement from the client that it does this without re-loading the app. Thanks! Thanks for any help you all can provide, it's driving me crazy not being able to figure this out."

    Read the article

  • Find files on a remote server

    - by Peter Kelly
    I have a web-service that resides on serverA. The webservice will be responsible for finding files of a certain type in a virtual directory on serverB and then returning the full URL to the files. I have the service working if the files are located on the same machine - this is straight-forward enough. My question is what is the best way to find all files of a certain type (say *.xml) in all directories below a known virtual directory on a remote server? So for example, the webservice is on http://ServerA/service.asmx and the virtual directory is located at http://serverB/virtualdirectory So in this code, obviously the DirectoryInfo will not take a path to the remote server - how do I access this so I can find the files it contains? How do I then get the full URL to a file found on that remote server? DirectoryInfo updateDirectory = new DirectoryInfo(path); FileInfo[] files = updateDirectory.GetFiles("*.xml", SearchOption.AllDirectories); foreach (FileInfo fileInfo in files) { // Get URL to the file } I cannot have the files and the service on the same server - IT decision that is out of my hands. Thanks!

    Read the article

  • Bridge or Factory and How

    - by Chris
    I'm trying to learn patterns and I've got a job that is screaming for a pattern, I just know it but I can't figure it out. I know the filter type is something that can be abstracted and possibly bridged. I'M NOT LOOKING FOR A CODE REWRITE JUST SUGGESTIONS. I'm not looking for someone to do my job. I would like to know how patterns could be applied to this example. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.IO; using System.Xml; using System.Text.RegularExpressions; namespace CopyTool { class CopyJob { public enum FilterType { TextFilter, RegExFilter, NoFilter } public FilterType JobFilterType { get; set; } private string _jobName; public string JobName { get { return _jobName; } set { _jobName = value; } } private int currentIndex; public int CurrentIndex { get { return currentIndex; } } private DataSet ds; public int MaxJobs { get { return ds.Tables["Job"].Rows.Count; } } private string _filter; public string Filter { get { return _filter; } set { _filter = value; } } private string _fromFolder; public string FromFolder { get { return _fromFolder; } set { if (Directory.Exists(value)) { _fromFolder = value; } else { throw new DirectoryNotFoundException(String.Format("Folder not found: {0}", value)); } } } private List<string> _toFolders; public List<string> ToFolders { get { return _toFolders; } } public CopyJob() { Initialize(); } private void Initialize() { if (ds == null) { ds = new DataSet(); } ds.ReadXml(Properties.Settings.Default.ConfigLocation); LoadValues(0); } public void Execute() { ExecuteJob(FromFolder, _toFolders, Filter, JobFilterType); } public void ExecuteAll() { string OrigPath; List<string> DestPaths; string FilterText; FilterType FilterWay; foreach (DataRow rw in ds.Tables["Job"].Rows) { OrigPath = rw["FromFolder"].ToString(); FilterText = rw["FilterText"].ToString(); switch (rw["FilterType"].ToString()) { case "TextFilter": FilterWay = FilterType.TextFilter; break; case "RegExFilter": FilterWay = FilterType.RegExFilter; break; default: FilterWay = FilterType.NoFilter; break; } DestPaths = new List<string>(); foreach (DataRow crw in rw.GetChildRows("Job_ToFolder")) { DestPaths.Add(crw["FolderPath"].ToString()); } ExecuteJob(OrigPath, DestPaths, FilterText, FilterWay); } } private void ExecuteJob(string OrigPath, List<string> DestPaths, string FilterText, FilterType FilterWay) { FileInfo[] files; switch (FilterWay) { case FilterType.RegExFilter: files = GetFilesByRegEx(new Regex(FilterText), OrigPath); break; case FilterType.TextFilter: files = GetFilesByFilter(FilterText, OrigPath); break; default: files = new DirectoryInfo(OrigPath).GetFiles(); break; } foreach (string fld in DestPaths) { CopyFiles(files, fld); } } public void MoveToJob(int RecordNumber) { Save(); LoadValues(RecordNumber - 1); } public void AddToFolder(string folderPath) { if (Directory.Exists(folderPath)) { _toFolders.Add(folderPath); } else { throw new DirectoryNotFoundException(String.Format("Folder not found: {0}", folderPath)); } } public void DeleteToFolder(int index) { _toFolders.RemoveAt(index); } public void Save() { DataRow rw = ds.Tables["Job"].Rows[currentIndex]; rw["JobName"] = _jobName; rw["FromFolder"] = _fromFolder; rw["FilterText"] = _filter; switch (JobFilterType) { case FilterType.RegExFilter: rw["FilterType"] = "RegExFilter"; break; case FilterType.TextFilter: rw["FilterType"] = "TextFilter"; break; default: rw["FilterType"] = "NoFilter"; break; } DataRow[] ToFolderRows = ds.Tables["Job"].Rows[currentIndex].GetChildRows("Job_ToFolder"); for (int i = 0; i <= ToFolderRows.GetUpperBound(0); i++) { ToFolderRows[i].Delete(); } foreach (string fld in _toFolders) { DataRow ToFolderRow = ds.Tables["ToFolder"].NewRow(); ToFolderRow["JobId"] = ds.Tables["Job"].Rows[currentIndex]["JobId"]; ToFolderRow["Job_Id"] = ds.Tables["Job"].Rows[currentIndex]["Job_Id"]; ToFolderRow["FolderPath"] = fld; ds.Tables["ToFolder"].Rows.Add(ToFolderRow); } } public void Delete() { ds.Tables["Job"].Rows.RemoveAt(currentIndex); LoadValues(currentIndex++); } public void MoveNext() { Save(); currentIndex++; LoadValues(currentIndex); } public void MovePrevious() { Save(); currentIndex--; LoadValues(currentIndex); } public void MoveFirst() { Save(); LoadValues(0); } public void MoveLast() { Save(); LoadValues(ds.Tables["Job"].Rows.Count - 1); } public void CreateNew() { Save(); int MaxJobId = 0; Int32.TryParse(ds.Tables["Job"].Compute("Max(JobId)", "").ToString(), out MaxJobId); DataRow rw = ds.Tables["Job"].NewRow(); rw["JobId"] = MaxJobId + 1; ds.Tables["Job"].Rows.Add(rw); LoadValues(ds.Tables["Job"].Rows.IndexOf(rw)); } public void Commit() { Save(); ds.WriteXml(Properties.Settings.Default.ConfigLocation); } private void LoadValues(int index) { if (index > ds.Tables["Job"].Rows.Count - 1) { currentIndex = ds.Tables["Job"].Rows.Count - 1; } else if (index < 0) { currentIndex = 0; } else { currentIndex = index; } DataRow rw = ds.Tables["Job"].Rows[currentIndex]; _jobName = rw["JobName"].ToString(); _fromFolder = rw["FromFolder"].ToString(); _filter = rw["FilterText"].ToString(); switch (rw["FilterType"].ToString()) { case "TextFilter": JobFilterType = FilterType.TextFilter; break; case "RegExFilter": JobFilterType = FilterType.RegExFilter; break; default: JobFilterType = FilterType.NoFilter; break; } if (_toFolders == null) _toFolders = new List<string>(); _toFolders.Clear(); foreach (DataRow crw in rw.GetChildRows("Job_ToFolder")) { AddToFolder(crw["FolderPath"].ToString()); } } private static FileInfo[] GetFilesByRegEx(Regex rgx, string locPath) { DirectoryInfo d = new DirectoryInfo(locPath); FileInfo[] fullFileList = d.GetFiles(); List<FileInfo> filteredList = new List<FileInfo>(); foreach (FileInfo fi in fullFileList) { if (rgx.IsMatch(fi.Name)) { filteredList.Add(fi); } } return filteredList.ToArray(); } private static FileInfo[] GetFilesByFilter(string filter, string locPath) { DirectoryInfo d = new DirectoryInfo(locPath); FileInfo[] fi = d.GetFiles(filter); return fi; } private void CopyFiles(FileInfo[] files, string destPath) { foreach (FileInfo fi in files) { bool success = false; int i = 0; string copyToName = fi.Name; string copyToExt = fi.Extension; string copyToNameWithoutExt = Path.GetFileNameWithoutExtension(fi.FullName); while (!success && i < 100) { i++; try { if (File.Exists(Path.Combine(destPath, copyToName))) throw new CopyFileExistsException(); File.Copy(fi.FullName, Path.Combine(destPath, copyToName)); success = true; } catch (CopyFileExistsException ex) { copyToName = String.Format("{0} ({1}){2}", copyToNameWithoutExt, i, copyToExt); } } } } } public class CopyFileExistsException : Exception { public string Message; } }

    Read the article

  • Blank space after file extension -> weird FileInfo behaviour

    - by Axarydax
    Somehow a file has appeared in one of my directories, and it has space at the end of its extension - its name is "test.txt ". The weird thing is that Directory.GetFiles() returns me the path of this file, but I'm unable to retrieve file information with FileInfo class. The error manifests here: DirectoryInfo di = new DirectoryInfo("c:\\somedir"); FileInfo fi = di.GetFileSystemInfos("test*")[0] as FileInfo; //correctly fi.FullName is "c:\somedir\test.txt " //but fi.Exists==false (!) Is FileInfo class broken? Can I somehow retrieve information about this file? I really don't know how did that file appear on my file system, and I am unable to recreate some more of them. All of my attempts to create a new file with this type of extension have failed, but now my program is crashing when encoutering it. I can easily handle the exception when finding the file, but boy am I curious about this!

    Read the article

  • Is it bad programming style to have a single, maybe common, generic exception?

    - by m0s
    Hi, so in my program I have parts where I use try catch blocks like this try { DirectoryInfo dirInfo = new DirectoryInfo(someString); //I don't know if that directory exists //I don't know if that string is valid path string... it could be anything //Some operations here } catch(Exception iDontCareWhyItFailed) { //Didn't work? great... we will say: somethings wrong, try again/next one } Of course I probably could do checks to see if the string is valid path (regex), then I would check if directory exists, then I could catch various exceptions to see why my routine failed and give more info... But in my program it's not really necessary. Now I just really need to know if this is acceptable, and what would a pro say/think about that. Thanks a lot for attention.

    Read the article

  • How to convert raw_input() into a directory?

    - by Azeworai
    Hi everyone, I just picked up IronPython and I've been trying to get this IronPython script going but I'm stuck at trying to get a Path input from raw_input to be a directory path. The first block of code is the broken one that I'm working on. import System from System import * from System.IO import * from System.Diagnostics import * inputDirectory = raw_input("Enter Input Directory's full path [eg. c:\\vid\\]: ") print ("In: "+inputDirectory) outputDirectory = inputDirectory +"ipod\\" print ("Out: "+outputDirectory) #create the default output directory for s in DirectoryInfo(inputDirectory).GetFiles("*.avi"): print s.FullName arg = String.Format('-i "{0}" -t 1 -c 1 -o "{1}" --preset="iPod"' , s.FullName, outputDirectory + s.Name.Replace(".avi", ".mp4")) print arg proc = Process.Start("C:\\Program Files\\Handbrake\\HandBrakeCLI.exe", arg) #path to handbrake goes here proc.WaitForExit() The following code block is what I have working at the moment. import System from System import * from System.IO import * from System.Diagnostics import * for s in DirectoryInfo("F:\\Tomorrow\\").GetFiles("*.avi"): arg = String.Format('-i "{0}" -t 1 -c 1 -o "{1}" --preset="iPod"' , s.FullName, "F:\\Tomorrow\\ipod\\" + s.Name.Replace(".avi", ".mp4")) print arg proc = Process.Start("C:\\Program Files\\Handbrake\\HandBrakeCLI.exe", arg) #path to handbrake goes here proc.WaitForExit() PS: Credit for the above working code goes to Joseph at jcooney.net

    Read the article

  • C#/.NET: Closing another process outside the main window

    - by eibhrum
    Hi, I just wanna ask your opinion/suggestion on how to 'terminate' a running application/process is C# Right now, I do have the following codes: Process myProcess; private void btnOpen_Click(object sender, RoutedEventArgs e) { DirectoryInfo di = new DirectoryInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.Programs)); myProcess = Process.Start(di + @"\Wosk\Wosk.appref-ms"); // opening a file coming for Startup Menu } private void btnClose_Click(object sender, RoutedEventArgs e) { myProcess.Kill(); // not working - Cannot process request because the process has exited } I also tried myProcess.Close(); but nothing's happening.

    Read the article

  • C#: Why am I getting "the process cannot access the file * because it is being used by another proce

    - by zxcvbnm
    I'm trying to convert bmp files in a folder to jpg, then delete the old files. The code works fine, except it can't delete the bmp's. DirectoryInfo di = new DirectoryInfo(args[0]); FileInfo[] files = di.GetFiles("*.bmp"); foreach (FileInfo file in files) { string newFile = file.FullName.Replace("bmp", "jpg"); Bitmap bm = (Bitmap)Image.FromFile(file.FullName); bm.Save(newFile, ImageFormat.Jpeg); } for (int i = 0; i < files.Length; i++) files[i].Delete(); The files aren't being used by another program/process like the error indicates, so I'm assuming the problem is here. But to me the code seems fine, since I'm doing everything sequentially. This is all that there is to the program too, so the error can't be caused by code elsewhere.

    Read the article

  • How to take first file name from a folder in C#

    - by riad
    Hi all, I need to get the first file name from a folder .How i do it in C#? My below code return all the file names.pls guide: DirectoryInfo di = new DirectoryInfo(imgfolderPath); foreach (FileInfo fi in di.GetFiles()) { if (fi.Name != "." && fi.Name != ".." && fi.Name != "Thumbs.db") { string fileName = fi.Name; string fullFileName = fileName.Substring(0, fileName.Length - 4); MessageBox.Show(fullFileName); } } I just need the first file name.pls guide thanks Riad

    Read the article

  • Is this bad style of programming(C#) ?

    - by m0s
    Hi, so in my program I have parts where I use try catch blocks like this try { DirectoryInfo dirInfo = new DirectoryInfo(someString); //I don't know if that directory exists //I don't know if that string is valid path string... it could be anything //Some operations here } catch(Exception iDontCareWhyItFailed) { //Didn't work? great... we will say: somethings wrong, try again/next one } Of course I probably could do checks to see if the string is valid path (regex), then I would check if directory exists, then I could catch various exceptions to see why my routine failed and give more info... But in my program it's not really necessary. Now I just really need to know if this is acceptable, and what would a pro say/think about that. Thanks a lot for attention.

    Read the article

  • How do i get a directory listing for a folder on the web?

    - by JimDel
    How do I get a directory listing for a folder on the web? I'm looking to download a group of small files from a folder on the web. I can do it easily with a a single file but I'm not sure how to do it for multiple files. If there was something similar to the code below but for a folder on the web I think I can do it. private void button1_Click(object sender, EventArgs e) { DirectoryInfo di = new DirectoryInfo("c:/myFolder"); FileInfo[] rgFiles = di.GetFiles("*.*"); foreach (FileInfo fi in rgFiles) { //Do Something with each of them } } Thanks

    Read the article

  • Attempted to perform an unauthorized operation

    - by Lefteris Gkinis
    Now I use the following code: Public Function SetACL(ByVal filename As String, ByVal account As String, ByVal sender As Object, ByVal e As System.EventArgs) As Boolean Try Dim rule As FileSystemAccessRule = New FileSystemAccessRule(account, FileSystemRights.Write, AccessControlType.Allow) Dim fp As PermissionSet = New PermissionSet(Permissions.PermissionState.Unrestricted) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.Read, filename)) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.Write, filename)) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.PathDiscovery, filename)) fp.Assert() Dim di As DirectoryInfo = New DirectoryInfo(Path.GetDirectoryName(filename)) SetACL = False Dim security As DirectorySecurity = di.GetAccessControl(AccessControlSections.Access) security.ModifyAccessRule(AccessControlModification.Add, rule, SetACL) di.SetAccessControl(security) Return SetACL Catch ex As Exception MessageBox.Show(ex.Message, "Set Security Sub", MessageBoxButtons.OK, MessageBoxIcon.Stop) Finalize() End Try End Function The Error of 'Attempted to perform an unauthorized operation' comes when i'm trying to execute the instraction Dim security As DirectorySecurity = di.GetAccessControl(AccessControlSections.Access) Please if anybody knows why that error comes here to respond

    Read the article

  • How to avoid the Windows (XP) Security Warning when launching a "DOS" command line within C#?

    - by Will Marcouiller
    This question is related to this initial question asked a little while ago. Now, that I have chosen the extracting tool, I'm iterating through a given in command line parameter directory and subdirectories to extract the compressed .zip files. private static void ExtractAll(DirectoryInfo _workingFolder) { if(_workingFolder == null) { Console.WriteLine("Répertoire inexistant."); return; } foreach (DirectoryInfo subFolder in _workingFolder.GetDirectories("*", SearchOption.AllDirectories)) foreach(FileInfo zippedFile in subFolder.GetFiles("*.zip", SearchOption.AllDirectories)) { if(zippedFile.Exists) { ProcessStartInfo task = new ProcessStartInfo(@".\Tools\7za.exe", string.Format("x {0}", zippedFile.FullName)); Process.Start(task); } } } But everytime I start a 7za process, the Windows Security Warning prompts. I would like to avoid such annoying behaviour, so here's my question: How to avoid the Windows (XP) Security Warning when launching a "DOS" command line within C#?

    Read the article

  • File System Types in .Net

    - by Avi
    I don't get the abstractions and the terminology :-( For example, DirectoryInfo.FullName is defined as the full path of the directory or file, but it's a string! So is DirectoryInfo.Name, FileInfo.FullName, Path.GetDirectoyName and so on. This means that in .Net there is no "depth" (or "meat" - my English isn't so good) for the file system objects. There's no protection from a type system. I can't, for example, define two Path objects and ask if one of them is "above" the other - I have to manipulate the strings. I can't differentiate between a Path that identifies a directory and a path that identifies a file. I can't do anything!-( Just manipulate strings. Is this correct (or am I simply missing something). If correct, are there any alternatives?

    Read the article

  • USB device Set Attribute in C#

    - by p19lord
    I have this bit of code: DriveInfo[] myDrives = DriveInfo.GetDrives(); foreach (DriveInfo myDrive in myDrives) { if (myDrive.DriveType == DriveType.Removable) { string path = Convert.ToString(myDrive.RootDirectory); DirectoryInfo mydir = new DirectoryInfo(path); String[] dirs = new string[] {Convert.ToString(mydir.GetDirectories())}; String[] files = new string[] {Convert.ToString(mydir.GetFiles())}; foreach (var file in files) { File.SetAttributes(file, ~FileAttributes.Hidden); File.SetAttributes(file, ~FileAttributes.ReadOnly); } foreach (var dir in dirs) { File.SetAttributes(dir, ~FileAttributes.Hidden); File.SetAttributes(dir, ~FileAttributes.ReadOnly); } } } I have a problem. It is trying the code for Floppy Disk drive first which and because no Floppy disk in it, it threw the error The device is not ready. How can I prevent that?

    Read the article

  • Help converting to C++ (6 replies)

    I have two lines of basic C# code System.IO.Directory.CreateDirectory(path); return System.IO.Directory.Exists(path); I want to bury this in a C Win32 Project. My effort so far (that does not work and I do not understand the error messages) is: #using mscorlib.dll using namespace System; using namespace System::IO; bool* clrcall;bool CDirectory(String path) { DirectoryInfo d Directory::CreateDirec...

    Read the article

  • Help converting to C++ (6 replies)

    I have two lines of basic C# code System.IO.Directory.CreateDirectory(path); return System.IO.Directory.Exists(path); I want to bury this in a C Win32 Project. My effort so far (that does not work and I do not understand the error messages) is: #using mscorlib.dll using namespace System; using namespace System::IO; bool* clrcall;bool CDirectory(String path) { DirectoryInfo d Directory::CreateDirec...

    Read the article

  • InvalidOperationException when calling SaveChanges in .NET Entity framework

    - by Pär Björklund
    Hi, I'm trying to learn how to use the Entity framework but I've hit an issue I can't solve. What I'm doing is that I'm walking through a list of Movies that I have and inserts each one into a simple database. This is the code I'm using private void AddMovies(DirectoryInfo dir) { MovieEntities db = new MovieEntities(); foreach (DirectoryInfo d in dir.GetDirectories()) { Movie m = new Movie { Name = d.Name, Path = dir.FullName }; db.AddToMovies(movie); } db.SaveChanges(); } When I do this I get an exception at db.SaveChanges() that read. The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges. I haven't been able to find out what's causing this issue. My database table contains three columns Id int autoincrement Name nchar(255) Path nchar(255) Update: I Checked my edmx file and the SSDL section have the StoreGeneratedPattern="Identity" as suggested. I also followed the blog post and tried to add ClientAutoGenerated="true" and StoreGenerated="true" in the CSDL as suggested there. This resulted in compile errors ( Error 5: The 'ClientAutoGenerated' attribute is not allowed.). Since the blog post is from 2006 and it has a link to a follow up post I assume it's been changed. However, I cannot read the followup post since it seems to require an msdn account.

    Read the article

  • Web application creation in IIS7 via MS.Web.Admin

    - by Jon Ownbey
    I am attempting to create seperate workflow instances as applications in IIS7 using the Microsoft.Web.Administration dll. When it attempts to add the Application to the Site ApplicationsCollection I get a COM error: "Invalid application path\r\n" using (ServerManager manager = new ServerManager()) { var site = manager.Sites.Where(x => x.Name == Properties.Settings.Default.WorkflowWebsiteName).Single(); StringBuilder stringBuilder = new StringBuilder() .Append(m_workflowDefinition.AccountId) .Append("/") .Append(m_workflowDefinition.WorkflowDefinitionId) .Append("/") .Append(m_workflowDefinition.Version) .Append("/"); string virtualPath = stringBuilder.ToString(); string physicalPath = Properties.Settings.Default.ApplicationPoolString + virtualPath.Replace("/", "\\"); if (!Directory.Exists(physicalPath)) Directory.CreateDirectory(physicalPath); //Create the workflow service definition file using (StreamWriter writer = new StreamWriter(Path.Combine(physicalPath, m_workflowDefinition.WorkflowName + WORKFLOW_FILE_EXTENSION))) { writer.Write(m_workflowDefinition.Definition); } //Copy dependencies string dependencyPath = m_workflowDefinition.DependenciesPath; CopyAll(new DirectoryInfo(dependencyPath), new DirectoryInfo(physicalPath)); //Create a new IIS application for the workflow var apps = site.Applications.Where(x => x.Path == virtualPath); if (apps.Count() > 0) { site.Applications.Remove(apps.Single()); } Application app = site.Applications.Add(virtualPath, physicalPath); app.ApplicationPoolName = "Workflow AppPool"; app.EnabledProtocols = PROTOCOLS; manager.CommitChanges(); } The value assigned to virtualPath is like: "something/something/something" and for physicalPath it is "c:\inetpub\wwwroot\Workflow\something\something\something". Any ideas? Any help is greatly appreciated.

    Read the article

  • System.InvalidOperationException: Failed to map the path '/sharedDrive/Public'

    - by d03boy
    I'm trying to set up a page that will allow users to download files from a shared drive (where the file is actually sent via the page). So far this is what I have. public partial class TestPage : System.Web.UI.Page { protected DirectoryInfo dir; protected FileInfo[] files; protected void Page_Load(object sender, EventArgs e) { dir = new DirectoryInfo(Server.MapPath(@"\\sharedDrive\Public")); files = dir.GetFiles(); } } The aspx page looks kind of like this: <% Response.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name); %> <ul> <% foreach (System.IO.FileInfo f in files) { Response.Write("<li>" + f.FullName + "</li>"); } %> </ul> When I remove the erroneous parts of the code, the page tells me that the Windows Identity I'm using is my user (which has access to the drive). I don't understand what the problem could be or what it's even complaining about.

    Read the article

  • How to implement an ListView containing images with style

    - by Alexandergre
    So I have been working with an app where I need to show the thumbnails as clean and use the space in a good way. Style A is my work until now. What I want to accomplish is something like style B. no titles and use the space in a good way. I need help with this. there was no tutorial on the net. Is ListView able to do such a thing? or shall I make picturesboxes and put them in a scrollview? the code: private void button1_Click(object sender, EventArgs e) { ImageList myImageList = new ImageList(); myImageList.ImageSize = new Size(48, 48); DirectoryInfo dir = new DirectoryInfo(@"C:\img"); foreach (FileInfo file in dir.GetFiles()) { try { myImageList.Images.Add(Image.FromFile(file.FullName)); } catch { Console.WriteLine("This is not an image file"); } } myListView.LargeImageList = myImageList; myListView.Items.Add("a", 0); myListView.Items.Add("b", 1); myListView.Items.Add("c", 2);

    Read the article

  • Access denied for pdf to read using itextsharp at server level..

    - by apekshabs
    Am facing error after uploadind to server... as access denied .... can anyone help me.... Document myDocument = new Document(PageSize.A5, 26, 72, 180, 180); string strUniqueFn = "onlineinvoice.pdf"; string imgpath = "logo.gif"; string strUser = Thread.CurrentPrincipal.Identity.Name.Substring(Thread.CurrentPrincipal.Identity.Name.IndexOf("\\") + 1).ToUpper(); string strFolder = Server.MapPath("."); System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(strFolder); System.IO.FileInfo[] fi = di.GetFiles(strUser + "*.*"); for (i = 0; i <= fi.Length - 1; i++) { System.IO.File.Delete(strFolder + "\\" + strUniqueFn); } string strPath = strFolder + "\\" + strUniqueFn; PdfWriter pdfw = PdfWriter.GetInstance(myDocument, new FileStream(strPath, FileMode.Create)); string iPath = strFolder + "\\" + imgpath; pdfw.CloseStream = false; myDocument.Open(); ...................... myDocument.Close(); Am facing error at PdfWriter pdfw = PdfWriter.GetInstance(myDocument, new FileStream(strPath, FileMode.Create)); can anyone help me... Thank you

    Read the article

  • IO operation taking long time for files in remote server

    - by user841311
    I have files of size 150 MB each in a remote server in a different domain in the network. I am accessing them thorugh UNC path. I want to read the file content and perform a basic string search. When I try reading the files line by line, the operation just don't finish and takes long time, more than 30 minutes. However when I copy those files to my local machine, the same code reads and performs the string search in less than 5 seconds. I don't have .NET framework installed in the server so I have to do this from my machine. I want to perform all this through C# code in .NET framework 3.5 so I don't want to explictly ftp all the files to my machine before performing this operation. Sample Code DirectoryInfo dir = new DirectoryInfo(@strFilePath); FileInfo[] fiArray = dir.getFiles("*.txt"); foreach (FileInfo fi in fiArray) { //reading file content from server takes long time but fast in local machine //perform string search } Let me know if my requirement is not clear. Thanks in advance!

    Read the article

  • GetAccessControl error with NTAccount

    - by Adam Witko
    private bool HasRights(FileSystemRights fileSystemRights_, string fileName_, bool isFile_) { bool hasRights = false; WindowsIdentity WinIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); WindowsPrincipal WinPrincipal = new WindowsPrincipal(WinIdentity); AuthorizationRuleCollection arc = null; if (isFile_) { FileInfo fi = new FileInfo(@fileName_); arc = fi.GetAccessControl().GetAccessRules(true, true, typeof(NTAccount)); } else { DirectoryInfo di = new DirectoryInfo(@fileName_); arc = di.GetAccessControl().GetAccessRules(true, true, typeof(NTAccount)); } foreach (FileSystemAccessRule rule in arc) { if (WinPrincipal.IsInRole(rule.IdentityReference.Value)) { if (((int)rule.FileSystemRights & (int)fileSystemRights_) > 0) { if (rule.AccessControlType == AccessControlType.Allow) hasRights = true; else if (rule.AccessControlType == AccessControlType.Deny) { hasRights = false; break; } } } } return hasRights; } The above code block is causing me problems. When the WinPrincipal.IsInRole(rule.IdentityReference.Value) is executed the following exception occurs: "The trust relationship between the primary domain and the trusted domain failed.". I'm very new to using identities, principles and such so I don't know what's the problem. I'm assuming it's with the use of NTAccount? Thanks

    Read the article

< Previous Page | 1 2 3 4  | Next Page >