Search Results

Search found 266 results on 11 pages for 'fileinfo'.

Page 2/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • File.Move error in C#

    - by Bi
    Hi I am trying a simple move as shown below and get the following error: "The process cannot access the file because it is being used by another process." How do I fix this? Thanks. FileInfo file1 = new FileInfo(srcFile); if (file1.Exists) { FileInfo file2 = new FileInfo(destFile); if (!file2.Exists) { try { File.Move(srcFile, destFile); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } }

    Read the article

  • WCF - CODEGEN: Generating message contract since message FileRequest has headers

    - by Tri Q
    I am aware that there is a similar question here with no solution. I'm working on a WCF streaming service over HTTP. Here are my MessageContract [MessageContract] public class FileRequest { #region Message Header [MessageHeader(MustUnderstand = true)] public Credential Credentials { get; set; } #endregion #region Message body [MessageBodyMember(Order = 1)] public FileInfo FileInfo { get; set; } #endregion #region Ctor // ... #endregion } [MessageContract] public class FileRequestResponse { #region Message Header [MessageHeader(MustUnderstand = true)] public FileInfo FileHeader { get; set; } [MessageHeader(MustUnderstand = true)] public OperationResult<bool> OperationResult { get; set; } #endregion #region Message Body [MessageBodyMember] public Stream FileStream { get; set; } #endregion #region Constructor // ... #endregion } Here is my ServiceContract [ServiceContract(Namespace = "https://service.contract.example.com")] public interface IUpdateService { [OperationContract(Action = "GetUpdates")] OperationResult<List<FileInfo>> GetUpates(ApplicationInfo applicationInfo, Credential credential); [OperationContract(Action = "GetFile")] FileRequestResponse FileRequest(FileRequest fileRequest); } Now the question is why I am getting this error: // CODEGEN: Generating message contract since message FileRequest has headers When I add my service reference. The end result is that the service contract wraps the FileRequest operation into a wrapper which I do not want. public FileInfo FileRequest(Credential Credentials, FileInfo, out OperationResult<bool> OperationResult, out System.IO.Stream FileStream) NOTE: I have not checked the "Always generate message contracts" in the service reference.

    Read the article

  • Uploading and Importing CSV file to SQL Server in ASP.NET WebForms

    - by Vincent Maverick Durano
    Few weeks ago I was working with a small internal project  that involves importing CSV file to Sql Server database and thought I'd share the simple implementation that I did on the project. In this post I will demonstrate how to upload and import CSV file to SQL Server database. As some may have already know, importing CSV file to SQL Server is easy and simple but difficulties arise when the CSV file contains, many columns with different data types. Basically, the provider cannot differentiate data types between the columns or the rows, blindly it will consider them as a data type based on first few rows and leave all the data which does not match the data type. To overcome this problem, I used schema.ini file to define the data type of the CSV file and allow the provider to read that and recognize the exact data types of each column. Now what is schema.ini? Taken from the documentation: The Schema.ini is a information file, used to define the data structure and format of each column that contains data in the CSV file. If schema.ini file exists in the directory, Microsoft.Jet.OLEDB provider automatically reads it and recognizes the data type information of each column in the CSV file. Thus, the provider intelligently avoids the misinterpretation of data types before inserting the data into the database. For more information see: http://msdn.microsoft.com/en-us/library/ms709353%28VS.85%29.aspx Points to remember before creating schema.ini:   1. The schema information file, must always named as 'schema.ini'.   2. The schema.ini file must be kept in the same directory where the CSV file exists.   3. The schema.ini file must be created before reading the CSV file.   4. The first line of the schema.ini, must the name of the CSV file, followed by the properties of the CSV file, and then the properties of the each column in the CSV file. Here's an example of how the schema looked like: [Employee.csv] ColNameHeader=False Format=CSVDelimited DateTimeFormat=dd-MMM-yyyy Col1=EmployeeID Long Col2=EmployeeFirstName Text Width 100 Col3=EmployeeLastName Text Width 50 Col4=EmployeeEmailAddress Text Width 50 To get started lets's go a head and create a simple blank database. Just for the purpose of this demo I created a database called TestDB. After creating the database then lets go a head and fire up Visual Studio and then create a new WebApplication project. Under the root application create a folder called UploadedCSVFiles and then place the schema.ini on that folder. The uploaded CSV files will be stored in this folder after the user imports the file. Now add a WebForm in the project and set up the HTML mark up and add one (1) FileUpload control one(1)Button and three (3) Label controls. After that we can now proceed with the codes for uploading and importing the CSV file to SQL Server database. Here are the full code blocks below: 1: using System; 2: using System.Data; 3: using System.Data.SqlClient; 4: using System.Data.OleDb; 5: using System.IO; 6: using System.Text; 7:   8: namespace WebApplication1 9: { 10: public partial class CSVToSQLImporting : System.Web.UI.Page 11: { 12: private string GetConnectionString() 13: { 14: return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString; 15: } 16: private void CreateDatabaseTable(DataTable dt, string tableName) 17: { 18:   19: string sqlQuery = string.Empty; 20: string sqlDBType = string.Empty; 21: string dataType = string.Empty; 22: int maxLength = 0; 23: StringBuilder sb = new StringBuilder(); 24:   25: sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName)); 26:   27: for (int i = 0; i < dt.Columns.Count; i++) 28: { 29: dataType = dt.Columns[i].DataType.ToString(); 30: if (dataType == "System.Int32") 31: { 32: sqlDBType = "INT"; 33: } 34: else if (dataType == "System.String") 35: { 36: sqlDBType = "NVARCHAR"; 37: maxLength = dt.Columns[i].MaxLength; 38: } 39:   40: if (maxLength > 0) 41: { 42: sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength)); 43: } 44: else 45: { 46: sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType)); 47: } 48: } 49:   50: sqlQuery = sb.ToString(); 51: sqlQuery = sqlQuery.Trim().TrimEnd(','); 52: sqlQuery = sqlQuery + " )"; 53:   54: using (SqlConnection sqlConn = new SqlConnection(GetConnectionString())) 55: { 56: sqlConn.Open(); 57: SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn); 58: sqlCmd.ExecuteNonQuery(); 59: sqlConn.Close(); 60: } 61:   62: } 63: private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter) 64: { 65: string sqlQuery = string.Empty; 66: StringBuilder sb = new StringBuilder(); 67:   68: sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName)); 69: sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath)); 70: sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter)); 71:   72: sqlQuery = sb.ToString(); 73:   74: using (SqlConnection sqlConn = new SqlConnection(GetConnectionString())) 75: { 76: sqlConn.Open(); 77: SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn); 78: sqlCmd.ExecuteNonQuery(); 79: sqlConn.Close(); 80: } 81: } 82: protected void Page_Load(object sender, EventArgs e) 83: { 84:   85: } 86: protected void BTNImport_Click(object sender, EventArgs e) 87: { 88: if (FileUpload1.HasFile) 89: { 90: FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName); 91: if (fileInfo.Name.Contains(".csv")) 92: { 93:   94: string fileName = fileInfo.Name.Replace(".csv", "").ToString(); 95: string csvFilePath = Server.MapPath("UploadedCSVFiles") + "\\" + fileInfo.Name; 96:   97: //Save the CSV file in the Server inside 'MyCSVFolder' 98: FileUpload1.SaveAs(csvFilePath); 99:   100: //Fetch the location of CSV file 101: string filePath = Server.MapPath("UploadedCSVFiles") + "\\"; 102: string strSql = "SELECT * FROM [" + fileInfo.Name + "]"; 103: string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'"; 104:   105: // load the data from CSV to DataTable 106:   107: OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString); 108: DataTable dtCSV = new DataTable(); 109: DataTable dtSchema = new DataTable(); 110:   111: adapter.FillSchema(dtCSV, SchemaType.Mapped); 112: adapter.Fill(dtCSV); 113:   114: if (dtCSV.Rows.Count > 0) 115: { 116: CreateDatabaseTable(dtCSV, fileName); 117: Label2.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName); 118:   119: string fileFullPath = filePath + fileInfo.Name; 120: LoadDataToDatabase(fileName, fileFullPath, ","); 121:   122: Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName); 123: } 124: else 125: { 126: LBLError.Text = "File is empty."; 127: } 128: } 129: else 130: { 131: LBLError.Text = "Unable to recognize file."; 132: } 133:   134: } 135: } 136: } 137: } The code above consists of three (3) private methods which are the GetConnectionString(), CreateDatabaseTable() and LoadDataToDatabase(). The GetConnectionString() is a method that returns a string. This method basically gets the connection string that is configured in the web.config file. The CreateDatabaseTable() is method that accepts two (2) parameters which are the DataTable and the filename. As the method name already suggested, this method automatically create a Table to the database based on the source DataTable and the filename of the CSV file. The LoadDataToDatabase() is a method that accepts three (3) parameters which are the tableName, fileFullPath and delimeter value. This method is where the actual saving or importing of data from CSV to SQL server happend. The codes at BTNImport_Click event handles the uploading of CSV file to the specified location and at the same time this is where the CreateDatabaseTable() and LoadDataToDatabase() are being called. If you notice I also added some basic trappings and validations within that event. Now to test the importing utility then let's create a simple data in a CSV format. Just for the simplicity of this demo let's create a CSV file and name it as "Employee" and add some data on it. Here's an example below: 1,VMS,Durano,[email protected] 2,Jennifer,Cortes,[email protected] 3,Xhaiden,Durano,[email protected] 4,Angel,Santos,[email protected] 5,Kier,Binks,[email protected] 6,Erika,Bird,[email protected] 7,Vianne,Durano,[email protected] 8,Lilibeth,Tree,[email protected] 9,Bon,Bolger,[email protected] 10,Brian,Jones,[email protected] Now save the newly created CSV file in some location in your hard drive. Okay let's run the application and browse the CSV file that we have just created. Take a look at the sample screen shots below: After browsing the CSV file. After clicking the Import Button Now if we look at the database that we have created earlier you'll notice that the Employee table is created with the imported data on it. See below screen shot.   That's it! I hope someone find this post useful! Technorati Tags: ASP.NET,CSV,SQL,C#,ADO.NET

    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

  • Using ExcelPacke to create Excel sheets on server

    - by DigiMortal
    In one of my community projects I needed to output some listings as Excel file. As installing Excel to server is non-sense that I was easily able to avoid I found simple solution for Excel 2007 files – open-source project called ExcelPackage. In this posting I will show you hot to create simple event attendees report in Excel 2007 format using ExcelPackage. Cautions Although ExcelPackage works well for me here are some things you should be aware of. ExcelPackage needs file system access because compression library it uses is designed so. There is only very old source code available and it is published under GPL. So if you are writing application to your customers then you cannot use this library unless you make your whole application open-source. ExcelPackage has also some technical problems and it is not very easy to use in simple cases. Authors have not provided any new releases since the beginning of 2007 so I have good reason to consider this project as abandoned. You may find the extensive package EPPlus also useful as there are new versions coming over time. EPPlus is also published under GPL (because ExcelPackage is under GPL), so you can use it only on very limited manner. If you don’t afraid some s*itfight with technology and GPL is okay for your system then let’s go on. Exporting event attendees list to Excel Suppose we have list with event attendees and we want to export it to Excel. We are behaving normally and we don’t install Excel desktop software to our web server. Here is the code. void ExportToExcel(Event evt) {     var fileInfo = new FileInfo(Path.GetTempPath() + "\\" +                                  DateTime.Now.Ticks + ".xlsx");       using (var xls = new ExcelPackage(fileInfo))     {         var sheet = xls.Workbook.Worksheets.Add(evt.Title);           sheet.Cell(1, 1).Value = "First name";         sheet.Cell(1, 2).Value = "Last name";         sheet.Cell(1, 3).Value = "E-mail";         sheet.Cell(1, 4).Value = "Phone";         sheet.Cell(1, 5).Value = "Registered";         sheet.Cell(1, 6).Value = "Live Meeting";           var i = 1;         foreach(var attendee in evt.Attendees)         {             i++;               var profile = attendee.Profile;             sheet.Cell(i, 1).Value = profile.FirstName;             sheet.Cell(i, 2).Value = profile.LastName;             sheet.Cell(i, 3).Value = profile.Email;             sheet.Cell(i, 4).Value = profile.Phone;             sheet.Cell(i, 5).Value = att.Created.ToString();             sheet.Cell(i, 6).Value = att.LiveMeeting.ToString();         }           xls.Save();      }       Response.Clear();     Response.ContentType = "application/vnd.openxmlformats";     Response.AddHeader("Content-Disposition",                        "attachment; filename=" + fileInfo.Name);     Response.WriteFile(fileInfo.FullName);     Response.Flush();       if (fileInfo.Exists)         fileInfo.Delete(); } And here is the result. Although it is possible to make this list more effective and nice it works and users can start using it until all the nice bells and whistles are coming. Conclusion After some fighting with technology it was not very hard to get nice Excel 2007 sheets coming out from our server. We used ExcelPackage library to create list of event attendees and our event organizers can now simply download data to Excel if they need to contact with attendees or manage their data using Excel tools.

    Read the article

  • C# : Parsing information out of a path

    - by mbcrump
    If you have a path for example: \\MyServer\MyFolderA\MyFolderB\MyFile.jpg and you need to parse out the filename, directory name or the directory parent name. You should use the fileinfo class instead of a regex expression or a string split. See the example code below:   Code Snippet using System; using System.IO;   class Test {     static void Main(string[] args)     {         string file = @"\\MyServer\MyFolderA\MyFolderB\MyFile.jpg";         FileInfo fi = new FileInfo(file);         Console.WriteLine(fi.Name);                  // Prints File.jpg         Console.WriteLine(fi.Directory.Name);        // Prints FolderB         Console.WriteLine(fi.Directory.Parent.Name); // Prints FolderA     } }

    Read the article

  • RhinoMocks AAA Syntax

    - by Bill Campbell
    Hi, I've spent a good part of the day trying to figure out why a simple RhinoMocks test doesn't return the value I'm setting in the return. I'm sure that I'm just missing something really simple but I can't figure it out. Here's my test: [TestMethod] public void CopyvRAFiles_ShouldCallCopyvRAFiles_ShouldReturnTrue2() { FileInfo fi = new FileInfo(@"c:\Myprogram.txt"); FileInfo[] myFileInfo = new FileInfo[2]; myFileInfo[0] = fi; myFileInfo[1] = fi; var mockSystemIO = MockRepository.GenerateMock<ISystemIO>(); mockSystemIO.Stub(x => x.GetFilesForCopy("c:")).Return(myFileInfo); mockSystemIO.Expect(y => y.FileCopyDateCheck(@"c:\Myprogram.txt", @"c:\Myprogram.txt")).Return("Test"); CopyFiles copy = new CopyFiles(mockSystemIO); List<string> retValue = copy.CopyvRAFiles("c:", "c:", new AdminWindowViewModel(vRASharedData)); mockSystemIO.VerifyAllExpectations(); } I have an interface for my SystemIO class I'm passing in a mock for that to my CopyFiles class. I'm setting an expectation on my FileCopyDatCheck method and saying that it should Return("Test"). When I step through the code, it returns a null insteaed. Any ideas what I'm missing here? Here's my CopyFiles class Method: public List<string> CopyvRAFiles(string currentDirectoryPath, string destPath, AdminWindowViewModel adminWindowViewModel) { string fileCopied; List<string> filesCopied = new List<string>(); try { sysIO.CreateDirectoryIfNotExist(destPath); FileInfo[] files = sysIO.GetFilesForCopy(currentDirectoryPath); if (files != null) { foreach (FileInfo file in files) { fileCopied = sysIO.FileCopyDateCheck(file.FullName, destPath + file.Name); filesCopied.Add(fileCopied); } } //adminWindowViewModel.CheckFilesThatRequireSystemUpdate(filesCopied); return filesCopied; } catch (Exception ex) { ExceptionPolicy.HandleException(ex, "vRAClientPolicy"); Console.WriteLine("{0} Exception caught.", ex); ShowErrorMessageDialog(ex); return null; } } I would think that "fileCopied" would have the Return value set by the Expect. The GetFilesForCopy returns the two files in myFileInfo. Please Help. :) thanks in advance!

    Read the article

  • File upload progress

    - by Cornelius
    I've been trying to track the progress of a file upload but keep on ending up at dead ends (uploading from a C# application not a webpage). I tried using the WebClient as such: class Program { static volatile bool busy = true; static void Main(string[] args) { WebClient client = new WebClient(); // Add some custom header information client.Credentials = new NetworkCredential("username", "password"); client.UploadProgressChanged += client_UploadProgressChanged; client.UploadFileCompleted += client_UploadFileCompleted; client.UploadFileAsync(new Uri("http://uploaduri/"), "filename"); while (busy) { Thread.Sleep(100); } Console.WriteLine("Done: press enter to exit"); Console.ReadLine(); } static void client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e) { busy = false; } static void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e) { Console.WriteLine("Completed {0} of {1} bytes", e.BytesSent, e.TotalBytesToSend); } } The file does upload and progress is printed out but the progress is much faster than the actual upload and when uploading a large file the progress will reach the maximum within a few seconds but the actual upload takes a few minutes (it is not just waiting on a response, all the data have not yet arrived at the server). So I tried using HttpWebRequest to stream the data instead (I know this is not the exact equivalent of a file upload as it does not produce multipart/form-data content but it does serve to illustrate my problem). I set AllowWriteStreamBuffering to false and set the ContentLength as suggested by this question/answer: class Program { static void Main(string[] args) { FileInfo fileInfo = new FileInfo(args[0]); HttpWebRequest client = (HttpWebRequest)WebRequest.Create(new Uri("http://uploadUri/")); // Add some custom header info client.Credentials = new NetworkCredential("username", "password"); client.AllowWriteStreamBuffering = false; client.ContentLength = fileInfo.Length; client.Method = "POST"; long fileSize = fileInfo.Length; using (FileStream stream = fileInfo.OpenRead()) { using (Stream uploadStream = client.GetRequestStream()) { long totalWritten = 0; byte[] buffer = new byte[3000]; int bytesRead = 0; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { uploadStream.Write(buffer, 0, bytesRead); uploadStream.Flush(); Console.WriteLine("{0} of {1} written", totalWritten += bytesRead, fileSize); } } } Console.WriteLine("Done: press enter to exit"); Console.ReadLine(); } } The request does not start until the entire file have been written to the stream and already shows full progress at the time it starts (I'm using fiddler to verify this). I also tried setting SendChunked to true (with and without setting the ContentLength as well). It seems like the data still gets cached before being sent over the network. Is there something wrong with one of these approaches or is there perhaps another way I can track the progress of file uploads from a windows application?

    Read the article

  • Access problems with System.Diagnostics.Process in webservice

    - by Martin
    Hello everyone. I have problems with executing a process in a webservice method on a Windows Server 2003 machine. Here is the code: Dim target As String = "C:\dnscmd.exe" Dim fileInfo As System.IO.FileInfo = New System.IO.FileInfo(target) If Not fileInfo.Exists Then Throw New System.IO.FileNotFoundException("The requested file was not found: " + fileInfo.FullName) End If Dim startinfo As New System.Diagnostics.ProcessStartInfo("C:\dnscmd.exe") startinfo.UseShellExecute = False startinfo.Arguments = "\\MYCOMPUTER /recordadd mydomain.no " & dnsname & " CNAME myhost.mydomain.no" startinfo.UserName = "user1" Dim password As New SecureString() For Each c As Char In "secretpassword".ToCharArray() password.AppendChar(c) Next startinfo.Password = password Process.Start(startinfo) I know the process is being executed because i use processmonitor.exe on the server and it tells me that c:\dnscmd.exe is called with the right parameters Full command line value from procmon is: "C:\dnscmd.exe" \MYCOMPUTER /recordadd mydomain.no mysubdomain CNAME myhost.mydomain.no The user of the created process on the server is NT AUTHORITY\SYSTEM. BUT, the dns entry will not be added! Here is the weird thing: I KNOW the user (user1) I authenticate with has administrative rights (it's the same user I use to log on the machine with), but the user of the process in procmon says NT AUTHORITY\SYSTEM (which is not the user i use to authenticate). Weirdest: If i log on to the server, copy the command line value read from the procmon logging, and paste it in a command line window, it works! Reading procmon after this shows that user1 owns the dnscmd process. Why doesn't user1 become owner of the process started with system.diagnostics.process? Is the reason why the command doesn't work?

    Read the article

  • [ASP.NET] IIS7 downloading file length

    - by GTD
    I've following code for file download: FileInfo fileInfo = new FileInfo(filePath); context.Response.Clear(); context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(filePath)); context.Response.AddHeader("Content-Length", fileInfo.Length.ToString()); context.Response.WriteFile(filePath); context.Response.End(); When I run it on my local IIS6 it works fine. Web browser (tested on IE8, Firefox 3.5.2, Opera 10) shows file length before I start download the file. When I run this code on remote IIS7, web browser doesn't shows file length. File length is unknown. Why I don't get file length when this code runs under IIS7?

    Read the article

  • File details from a string in C#

    - by acadia
    Hello, I have a string in C# String file="\\mserver-80\docs\somedoc.doc" Now How do I get fileInfo from the above sting. What I mean is, I want to declare something like FileInfo fInfo = new FileInfo(file); fileExtn = fInfo.Extension;

    Read the article

  • C#: How to gracefully pass multiple conditions to Equals()

    - by Roy
    I'm new to C#, and I'm trying to write a program that selects file types from a FileInfo list. So far I have something along the lines of: List<FileInfo> files = new List<FileInfo>(); IEnumerable<FileInfo> result = files.Where(f=>f.Extension.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase)|| f.Extension.Equals(".gif", StringComparison.InvariantCultureIgnoreCase) ); etc Obviously I'm not happy with this solution, but I don't know how to do this otherwise in a single call. What's the better way to go about it?

    Read the article

  • Static Logger in seperate thread?

    - by SirLenz0rlot
    Hi all, I've made my Logger, that logs a string, a static class with a static so I can call it from my entire project without having to make an instance of it. quite nice, but I want to make it run in a seperate thread, since accessing the file costs time is that possible somehow and what's the best way to do it? Its a bit of a short discription, but I hope the idea is clear. if not, please let me know. Thanks in advance! btw: any other improvements on my code are welcome as well, i have the feeling not everthing is as efficient as it can be: internal static class MainLogger { internal static void LogStringToFile(string logText) { DateTime timestamp = DateTime.Now; string str = timestamp.ToString("dd-MM-yy HH:mm:ss ", CultureInfo.InvariantCulture) + "\t" + logText + "\n"; const string filename = Constants.LOG_FILENAME; FileInfo fileInfo = new FileInfo(filename); if (fileInfo.Exists) { if (fileInfo.Length > Constants.LOG_FILESIZE) { File.Create(filename).Dispose(); } } else { File.Create(filename).Dispose(); } int i = 0; while(true) { try { using (StreamWriter writer = File.AppendText(filename)) { writer.WriteLine(str); } break; } catch (IOException) { Thread.Sleep(10); i++; if (i >= 8) { throw new IOException("Log file \"" + Constants.LOG_FILENAME + "\" not accessible after 5 tries"); } } } } } enter code here

    Read the article

  • Check directory exists and if it doesnt choose an image

    - by Andy
    I have this code so far which perfectly but relies on there being a directory in place: $path = '/home/sites/therealbeercompany.co.uk/public_html/public/themes/trbc/images/backgrounds/'.$this->slug; $bgimagearray = array(); $iterator = new DirectoryIterator($path); foreach ($iterator as $fileinfo) { if ($fileinfo->isFile() && !preg_match('\.jpg$/', $fileinfo->getFilename())) { $bgimagearray[] = "'" . $fileinfo->getFilename() . "'"; } } I need to work in a bit at the top so that if the directory doesnt exist it defaults to the images sat in the root of the background directory... Any help would be appreciated.

    Read the article

  • Read video information(date created)?

    - by Lynx
    In window, i can get the date created of the video from properties(right click). I have a few idea on this but i dont know how to do it. 1. Get the video information directly from video(like in windows), 2. By extracting the video name to get the date created(The video's name is in date format, which is the time it created). And i also using taglib-sharp to get the video duration and resolution, but i cant find any sample code on how to get the video creation date. Note: video name in date format - example, 20121119_125550.avi Edit Found this code and so far its working string fileName = Server.MapPath("//video//20121119_125550.avi"); FileInfo fileInfo = new FileInfo(fileName); DateTime creationTime = fileInfo.CreationTime; Output: 2012/11/19 12:55:50 For the file's name, i will add another string in name. For example User1-20121119_125550.avi.avi, so it will get complicated after that.

    Read the article

  • XDocument + IEnumerable is causing out of memory exception in System.Xml.Linq.dll

    - by Manatherin
    Basically I have a program which, when it starts loads a list of files (as FileInfo) and for each file in the list it loads a XML document (as XDocument). The program then reads data out of it into a container class (storing as IEnumerables), at which point the XDocument goes out of scope. The program then exports the data from the container class to a database. After the export the container class goes out of scope, however, the garbage collector isn't clearing up the container class which, because its storing as IEnumerable, seems to lead to the XDocument staying in memory (Not sure if this is the reason but the task manager is showing the memory from the XDocument isn't being freed). As the program is looping through multiple files eventually the program is throwing a out of memory exception. To mitigate this ive ended up using System.GC.Collect(); to force the garbage collector to run after the container goes out of scope. this is working but my questions are: Is this the right thing to do? (Forcing the garbage collector to run seems a bit odd) Is there a better way to make sure the XDocument memory is being disposed? Could there be a different reason, other than the IEnumerable, that the document memory isnt being freed? Thanks. Edit: Code Samples: Container Class: public IEnumerable<CustomClassOne> CustomClassOne { get; set; } public IEnumerable<CustomClassTwo> CustomClassTwo { get; set; } public IEnumerable<CustomClassThree> CustomClassThree { get; set; } ... public IEnumerable<CustomClassNine> CustomClassNine { get; set; }</code></pre> Custom Class: public long VariableOne { get; set; } public int VariableTwo { get; set; } public DateTime VariableThree { get; set; } ... Anyway that's the basic structures really. The Custom Classes are populated through the container class from the XML document. The filled structures themselves use very little memory. A container class is filled from one XML document, goes out of scope, the next document is then loaded e.g. public static void ExportAll(IEnumerable<FileInfo> files) { foreach (FileInfo file in files) { ExportFile(file); //Temporary to clear memory System.GC.Collect(); } } private static void ExportFile(FileInfo file) { ContainerClass containerClass = Reader.ReadXMLDocument(file); ExportContainerClass(containerClass); //Export simply dumps the data from the container class into a database //Container Class (and any passed container classes) goes out of scope at end of export } public static ContainerClass ReadXMLDocument(FileInfo fileToRead) { XDocument document = GetXDocument(fileToRead); var containerClass = new ContainerClass(); //ForEach customClass in containerClass //Read all data for customClass from XDocument return containerClass; } Forgot to mention this bit (not sure if its relevent), the files can be compressed as .gz so I have the GetXDocument() method to load it private static XDocument GetXDocument(FileInfo fileToRead) { XDocument document; using (FileStream fileStream = new FileStream(fileToRead.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (String.Compare(fileToRead.Extension, ".gz", true) == 0) { using (GZipStream zipStream = new GZipStream(fileStream, CompressionMode.Decompress)) { document = XDocument.Load(zipStream); } } else { document = XDocument.Load(fileStream); } return document; } } Hope this is enough information. Thanks Edit: The System.GC.Collect() is not working 100% of the time, sometimes the program seems to retain the XDocument, anyone have any idea why this might be?

    Read the article

  • There's a black hole in my server (TcpClient, TcpListener)

    - by Matías
    Hi, I'm trying to build a server that will receive files sent by clients over a network. If the client decides to send one file at a time, there's no problem, I get the file as I expected, but if it tries to send more than one I only get the first one. Here's the server code: I'm using one Thread per connected client public void ProcessClients() { while (IsListening) { ClientHandler clientHandler = new ClientHandler(listener.AcceptTcpClient()); Thread thread = new Thread(new ThreadStart(clientHandler.Process)); thread.Start(); } } The following code is part of ClientHandler class public void Process() { while (client.Connected) { using (MemoryStream memStream = new MemoryStream()) { int read; while ((read = client.GetStream().Read(buffer, 0, buffer.Length)) > 0) { memStream.Write(buffer, 0, read); } if (memStream.Length > 0) { Packet receivedPacket = (Packet)Tools.Deserialize(memStream.ToArray()); File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Guid.NewGuid() + receivedPacket.Filename), receivedPacket.Content); } } } } On the first iteration I get the first file sent, but after it I don't get anything. I've tried using a Thread.Sleep(1000) at the end of every iteration without any luck. On the other side I have this code (for clients) . . client.Connect(); foreach (var oneFilename in fileList) client.Upload(oneFilename); client.Disconnect(); . . The method Upload: public void Upload(string filename) { FileInfo fileInfo = new FileInfo(filename); Packet packet = new Packet() { Filename = fileInfo.Name, Content = File.ReadAllBytes(filename) }; byte[] serializedPacket = Tools.Serialize(packet); netStream.Write(serializedPacket, 0, serializedPacket.Length); netStream.Flush(); } netStream (NetworkStream) is opened on Connect method, and closed on Disconnect. Where's the black hole? Can I send multiple objects as I'm trying to do? Thanks for your time.

    Read the article

  • How upload files to azure in background with Delphi and OmniThread?

    - by mamcx
    I have tried to upload +100 files to azure with Delphi. However, the calls block the main thread, so I want to do this with a async call or with a background thread. This is what I do now (like explained here): procedure TCloudManager.UploadTask(const input: TOmniValue; var output: TOmniValue); var FileTask:TFileTask; begin FileTask := input.AsRecord<TFileTask>; Upload(FileTask.BaseFolder, FileTask.LocalFile, FileTask.CloudFile); end; function TCloudManager.MassiveUpload(const BaseFolder: String; Files: TDictionary<String, String>): TStringList; var pipeline: IOmniPipeline; FileInfo : TPair<String,String>; FileTask:TFileTask; begin // set up pipeline pipeline := Parallel.Pipeline .Stage(UploadTask) .NumTasks(Environment.Process.Affinity.Count * 2) .Run; // insert URLs to be retrieved for FileInfo in Files do begin FileTask.LocalFile := FileInfo.Key; FileTask.CloudFile := FileInfo.Value; FileTask.BaseFolder := BaseFolder; pipeline.Input.Add(TOmniValue.FromRecord(FileTask)); end;//for pipeline.Input.CompleteAdding; // wait for pipeline to complete pipeline.WaitFor(INFINITE); end; However this block too (why? I don't understand).

    Read the article

  • Stuck trying to get Log4Net to work with Dependency Injection

    - by Pure.Krome
    I've got a simple winform test app i'm using to try some Log4Net Dependency Injection stuff. I've made a simple interface in my Services project :- public interface ILogging { void Debug(string message); // snip the other's. } Then my concrete type will be using Log4Net... public class Log4NetLogging : ILogging { private static ILog Log4Net { get { return LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); } } public void Debug(string message) { if (Log4Net.IsDebugEnabled) { Log4Net.Debug(message); } } } So far so good. Nothing too hard there. Now, in a different project (and therefore namesapce), I try and use this ... public partial class Form1 : Form { public Form1() { FileInfo fileInfo = new FileInfo("Log4Net.config"); log4net.Config.XmlConfigurator.Configure(fileInfo); } private void Foo() { // This would be handled with DI, but i've not set it up // (on the constructor, in this code example). ILogging logging = new Log4NetLogging(); logging.Debug("Test message"); } } Ok .. also pretty simple. I've hardcoded the ILogging instance but that is usually dependency injected via the constructor. Anyways, when i check this line of code... return LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); the DeclaringType type value is of the Service namespace, not the type of the Form (ie. X.Y.Z.Form1) which actually called the method. Without passing the type INTO method as another argument, is there anyway using reflection to figure out the real method that called it?

    Read the article

  • Read all sub directories within a certain folder to display a random image.

    - by Andy
    I have this code i have been using....but i need a conditional where it will read all the sub directories of /bg to select an image as opposed to a specific folder if they were on a subpage. Heres my code so far which works perfectly for all subpages to display specific images: //This would tell us its on the homepage if it helps: $this->level() == 0 //This is the code so far $path = '/home/sites/mydomain.co.uk/public_html/public/images/bg/'.$this->slug; $homepagefile = URL_PUBLIC.'public/images/bg/'.$this->slug.'/main.jpg'; $bgimagearray = array(); $iterator = new DirectoryIterator($path); foreach ($iterator as $fileinfo) { if ($fileinfo->isFile() && !preg_match('\.jpg$/', $fileinfo->getFilename())) { $bgimagearray[] = "'" . $fileinfo->getFilename() . "'"; } } $bgimage = array_rand($bgimagearray); ?> <div id="bg"> <div> <table cellspacing="0" cellpadding="0"> <tr> <td><img src="<?php echo $file.trim($bgimagearray[$bgimage], "'"); ?>" alt=""/></td> </tr> </table> </div> </div> Any help would be appreciated, im sure its not rocket science but ive tried a few ways and cant get my head around it. Thanks in advance.

    Read the article

  • Make an abstract class or use a processor?

    - by Tim Murphy
    I'm developing a class to compare two directories and run an action when a directory/file in the source directory does not exist in destination directory. Here is a prototype of the class: public abstract class IdenticalDirectories { private DirectoryInfo _sourceDirectory; private DirectoryInfo _destinationDirectory; protected abstract void DirectoryExists(DirectoryInfo sourceDirectory, DirectoryInfo destinationDirectory); protected abstract void DirectoryDoesNotExist(DirectoryInfo sourceDirectory, DirectoryInfo destinationDirectory); protected abstract void FileExists(DirectoryInfo sourceDirectory, DirectoryInfo destinationDirectory); protected abstract void FileDoesNotExist(DirectoryInfo sourceDirectory, DirectoryInfo destinationDirectory); public IdenticalDirectories(DirectoryInfo sourceDirectory, DirectoryInfo destinationDirectory) { ... } public void Run() { foreach (DirectoryInfo sourceSubDirectory in _sourceDirectory.GetDirectories()) { DirectoryInfo destinationSubDirectory = this.GetDestinationDirectoryInfo(subDirectory); if (destinationSubDirectory.Exists()) { this.DirectoryExists(sourceSubDirectory, destinationSubDirectory); } else { this.DirectoryDoesNotExist(sourceSubDirectory, destinationSubDirectory); } foreach (FileInfo sourceFile in sourceSubDirectory.GetFiles()) { FileInfo destinationFile = this.GetDestinationFileInfo(sourceFile); if (destinationFile.Exists()) { this.FileExists(sourceFile, destinationFile); } else { this.FileDoesNotExist(sourceFile, destinationFile); } } } } } The above prototype is an abstract class. I'm wondering if it would be better to make the class non-abstract and have the Run method receiver a processor? eg. public void Run(IIdenticalDirectoriesProcessor processor) { foreach (DirectoryInfo sourceSubDirectory in _sourceDirectory.GetDirectories()) { DirectoryInfo destinationSubDirectory = this.GetDestinationDirectoryInfo(subDirectory); if (destinationSubDirectory.Exists()) { processor.DirectoryExists(sourceSubDirectory, destinationSubDirectory); } else { processor.DirectoryDoesNotExist(sourceSubDirectory, destinationSubDirectory); } foreach (FileInfo sourceFile in sourceSubDirectory.GetFiles()) { FileInfo destinationFile = this.GetDestinationFileInfo(sourceFile); if (destinationFile.Exists()) { processor.FileExists(sourceFile, destinationFile); } else { processor.FileDoesNotExist(sourceFile, destinationFile); } } } } What do you see as the pros and cons of each implementation?

    Read the article

  • Problems with php:(

    - by Marin
    Please help me again! I have problems with this code: <?php $pathThemes = INC_DIR . "themes"; $d = dir($pathThemes); while (false !== ($entry = $d->read())) { $fileInfo = pathinfo($pathThemes . '/' . $entry); if ('php' == $fileInfo['extension']) { include_once($pathThemes . '/' . $entry); $name = $fileInfo['filename']; if (!$GLOBALS['fc_config']['themes'][$name]['name']) { unset($GLOBALS['fc_config']['themes'][$name]); } } } ?> It says me: Notice: Undefined index: name in C:\wamp\www\FlashChat_v607\chat\inc\include_themes.php on line 10 Notice: Undefined index: name in C:\wamp\www\FlashChat_v607\chat\inc\include_themes.php on line 10 Notice: Undefined index: name in C:\wamp\www\FlashChat_v607\chat\inc\include_themes.php on line 10 Notice: Undefined index: name in C:\wamp\www\FlashChat_v607\chat\inc\include_themes.php on line 10 Help me plz;(

    Read the article

  • Is there an easier way to reconcile a list of files and a directory with subfolders/files to find ch

    - by rwmnau
    I have a SQL Server table with a list of files (path + filename), and a folder with multiple layers and files in each layer. I'm looking for a way to reconcile the two without having to process the list twice. Currently, I'm doing this: For Each f as FileInfo In FileListFromDatabase If f.Exists is False, mark it as deleted in the database Next For Each f as FileInfo In RecursiveListOFFilesOnDisk If Not FileExistsInDatabase, then add it Next Is there a better way to do this? I'd like to avoid converting all the matching files (of which most will be) to FileInfo objects twice. Since I'm a T-SQL developer first, I'm picturing something like an OUTER JOIN of the two lists where they don't match. Something LINQ-ish?

    Read the article

  • How to look for different types of files in a directory?

    - by herrow
    public List<string> MapMyFiles() { List<FileInfo> batchaddresses = new List<FileInfo>(); foreach (object o in lstViewAddresses.Items) { try { string[] files = Directory.GetFiles(o.ToString(), "*-E.esy"); files.ToList().ForEach(f => batchaddresses.Add(new FileInfo(f))); } catch { if(MessageBox.Show(o.ToString() + " does not exist. Process anyway?", "Continue?", MessageBoxButtons.YesNo) == DialogResult.Yes) { } else { Application.Exit(); } } } return batchaddresses.OrderBy(f => f.CreationTime) .Select(f => f.FullName).ToList(); } i would like to add to the array not only .ESY but also "p-.csv" how do i do this?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >