powered by simpleCommunicator - 2.0.49     © 2025 Programmizd 02
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / The process cannot access the file '' because it is being used by another process.
6 сообщений из 6, страница 1 из 1
The process cannot access the file '' because it is being used by another process.
    #39890649
stek...
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Привествую , друзья,

толи FileStream толи Process, помогите разобраться.
Указанное ниже windows forms приложение сперва выбирает один или несколько файлов из openFileDialog1, проверяет были ли эти файлы в БД, записывает их в БД . Затем читает из нее их и записывает в Windows. Далее произходит открытие этих файлов, закрытие и затем посылка их по Email.



Все работает вроде нормально, но когда выбираются файлы повторно или файлы в формате Excel выходит это исключение


The process cannot access the file '' because it is being used by another process.

При прогоне программы я нажимаю всего один раз кнопку (btnSales_Click.) В первый раз все проходит нормально.


Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
381.
382.
383.
384.
385.
386.
387.
388.
389.
390.
391.
392.
393.
394.
395.
396.
397.
398.
399.
400.
401.
 [code=c#]
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Globalization;
using System.Diagnostics;
using System.Net;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Net.Mime;
//using System.Threading.Tasks;


namespace GebrNaimSalesWindowsForms
{
    public partial class Form1 : Form
    {
        //SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-E2S6MTB\SQLEXPRESS;Initial Catalog=GebrNaimProject;Integrated Security=True");

        //SqlDataAdapter adapt;
        //public string[] files { get; set; }
        public List<string> files { get; set; }
        public List<string> outputfiles { get; set; }
        public int insertNummer;
        public int row_id;
        public Process sp;
        public string ExceptionMessage { get; set; }

        public Form1()
        {
            InitializeComponent();
            //DisplayData();
        }

        //Display Data in DataGridView  
        //private void DisplayData()
        //{
        //    con.Open();
        //    DataTable dt = new DataTable();
        //    adapt = new SqlDataAdapter("select * from StoredFile", con);
        //    adapt.Fill(dt);
        //    dataGridView1.DataSource = dt;
        //    con.Close();
        //}
        private void btnSales_Click(object sender, EventArgs e)
        {
            outputfiles = null;
            files = null;
            sp = null;
            
            //sp.Refresh();

            if (InformationWindow("Выбирете пожалйста фалы и сохраните в Windows", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.OK)
            {

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    foreach (var item in openFileDialog1.FileNames)
                    {
                        //files.Add(item);

                        files = new List<string>();
                        files.Add(item);

                    }
                    
                  
                }
                else
                {
                    files = null;
                }

                GetInsertNummer(@"SELECT (SELECT MAX(id) FROM StoredFile) id, MAX(InsertNummer) InsertNummer
FROM StoredFile");

                if (files != null)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        InsertInTable(i);

                        row_id++;


                        FileGetSimple(row_id, files[i]);
                      
                    }
                    InformationWindow("Все в порядке с выбранными файлами?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    CreateMessage("smtp.strato.de");

                    MessageBox.Show("success");


                }

                //DisplayData();


            }


        }

        public DialogResult InformationWindow(string v1, string v2, MessageBoxButtons oKCancel, MessageBoxIcon information)
        {
            string message = v2;
            string caption = v1;
            MessageBoxButtons buttons = oKCancel;
            DialogResult result;

            // Displays the MessageBox.
            return result = MessageBox.Show(message, caption, buttons, information);
        }



        public void CreateMessage(string server)
        {
            using (SmtpClient client = new SmtpClient(server))
            {

                client.Port = 587;
                client.EnableSsl = true;
                
                client.Credentials = new NetworkCredential("s.dadashev@gebr-naim.de", "");

                MailAddress from = new MailAddress("---",--- );
                MailAddress to = new MailAddress("---", ---);
                MailMessage message = new MailMessage(from, to);

                // message.Subject = "Using the SmtpClient class.";
                message.Subject = "Es funktioniert.";
                message.Body = @"Вы получили письмо с вложением";

                foreach (var item in outputfiles)
                {
                    if (!sp.HasExited)
                    {
                        //sp.WaitForExit();
                        sp.Kill();
                        

                        //if (Marshal.IsComObject(sp))
                        //{
                        //    Marshal.ReleaseComObject(sp);
                        //}

                        
                        //Marshal.ReleaseComObject(sp);
                    }
                    else
                        sp = null;
                    //sp.WaitForExit();
                    //sp.Close();

                    //Process[] ps2 = System.Diagnostics.Process.GetProcessesByName("EXCEL");
                    //foreach (Process p2 in ps2)
                    //{
                    //    Marshal.ReleaseComObject(p2);
                    //    p2.Kill();
                    //}

                    message.Attachments.Add(new Attachment(item));


                }


                InformationWindow("Success", $"Sending an email message to" + to.Address + " by using the SMTP host " + client.Host + ".", MessageBoxButtons.OK, MessageBoxIcon.Information);

                try
                {
                    client.Send(message);
                }
                catch (Exception ex)
                {
                    // Me.WriteLine("Exception caught in CreateCopyMessage(): {0}",ex.ToString());
                    InformationWindow("Exception", ex.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
               //
            }
        }

  

//using(SmtpClient smtpClient = new SmtpClient())
//{
//    var basicCredential = new NetworkCredential("username", "password"); 
//    using(MailMessage message = new MailMessage())
//    {
//        MailAddress fromAddress = new MailAddress("from@yourdomain.com");

//        smtpClient.Host = "mail.mydomain.com";
//        smtpClient.UseDefaultCredentials = false;
//        smtpClient.Credentials = basicCredential;

//        message.From = fromAddress;
//        message.Subject = "your subject";
//        // Set IsBodyHtml to true means you can send HTML email.
//        message.IsBodyHtml = true;
//        message.Body = "<h1>your message body</h1>";
//        message.To.Add("to@anydomain.com"); 

//        try
//        {
//            smtpClient.Send(message);
//        }
//        catch(Exception ex)
//        {
//            //Error, could not send the message
//            Response.Write(ex.Message);
//        }
//    }
//}



        private void InsertInTable(int i)
        {
            // **** Write BLOB to the Database
            byte[] filebyte = File.ReadAllBytes(files[i]);

            string sql = @"insert into StoredFile(FileName,Data,InsertNummer,Date) values(@FileName,@Data,@InsertNummer,@Date)";

            var cmd = MakeConnection(sql);

            SqlParameter parameter1 = cmd.Parameters.AddWithValue("@FileName", Path.GetFileName(files[i]));
            SqlParameter parameter2 = cmd.Parameters.AddWithValue("@Data", filebyte);
            SqlParameter parameter3 = cmd.Parameters.AddWithValue("@InsertNummer", insertNummer);
            SqlParameter parameter4 = cmd.Parameters.AddWithValue("@Id", row_id);
            SqlParameter parameter5 = cmd.Parameters.AddWithValue("@Date", DateTime.Now);


            cmd.ExecuteNonQuery();
            

          
        }

        public bool FileGetSimple(int Identifier, string filePath)
        {
            var pa = Path.Combine(Path.GetTempPath(), Path.GetFileName(filePath));

            var statement = "SELECT Id, Data, FileName FROM StoredFile WHERE Id = @id;";
            var mc = MakeConnection(statement);
         

            mc.Parameters.AddWithValue("@id", Identifier);
            SqlDataReader reader = mc.ExecuteReader();

            if (reader.HasRows)
            {
                reader.Read();

                // the blob field
                int ndx = reader.GetOrdinal("Data");

                var blob = new Byte[(reader.GetBytes(ndx, 0, null, 0, int.MaxValue))];

                reader.GetBytes(ndx, 0, blob, 0, blob.Length);
                reader.Close();

                try
                {
                    //using (var fs = new FileStream(pa, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                    //{
                    //    fs.Write(blob, 0, blob.Length);
                    //}

                    if (File.Exists(pa))
                    {
                        File.Delete(pa);
                    }

                    using (var fs = new FileStream(pa, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                    {
                        fs.Write(blob, 0, blob.Length);

                    }


                    

                    //using (FileStream fs = File.Create(pa))
                    //{
                    //    fs.Write(blob, 0, blob.Length);
                    //}

                    //using (var stream = File.Create(pa))
                    //{
                    //File.WriteAllBytes(pa, blob);
                    //}
                }
                catch (IOException e) {
                    InformationWindow("Warning", e.Message + " Schlie&#223;en Sie diese Datei, um fortzusetzen.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    FileGetSimple(Identifier, filePath);
                }

   


                
            }



            OpenFiles(pa);

            return true;

        }

        private void OpenFiles(string tempFilePath)
        {
            

            using (sp = new Process())
            {
                sp = Process.Start(tempFilePath);
            }



            outputfiles = new List<string>();
            outputfiles.Add(tempFilePath);

        }

        public void GetInsertNummer(string ins_num_query)
        {

            var ins_num = MakeConnection(ins_num_query);
            SqlDataReader read_ins_nummer = ins_num.ExecuteReader();

            while (read_ins_nummer.Read())
            {
                int ins = read_ins_nummer.GetOrdinal("InsertNummer");
                int ins_id = read_ins_nummer.GetOrdinal("Id");
                if (!read_ins_nummer.IsDBNull(read_ins_nummer.GetOrdinal("InsertNummer")))
                {
                    insertNummer = read_ins_nummer.GetInt32(ins);
                    row_id = read_ins_nummer.GetInt32(ins_id);
                    insertNummer++;
                }
                else
                {
                    insertNummer = 1;
                    row_id = 0;
                }

            }
        }



        public SqlCommand MakeConnection(string sql)
        {

            SqlConnection connection = new SqlConnection(Properties.Settings.Default.connection_str);
            connection.Open();


            using (SqlCommand cmd = new SqlCommand() { Connection = connection, CommandText = sql })
            {
                try
                {
                    return cmd;

                }
                catch (Exception ex)
                {

                    ExceptionMessage = ex.Message;
                    return cmd;
                }
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //this.Close();
            Application.Exit();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'gebrNaimProjectDataSet.StoredFile' table. You can move, or remove it, as needed.
            //this.storedFileTableAdapter.Fill(this.gebrNaimProjectDataSet.StoredFile);

        }
    }
}

...
Рейтинг: 0 / 0
The process cannot access the file '' because it is being used by another process.
    #39890665
Roman Mejtes
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
переводить ошибку на русский не пробовали?
ошибка сообщает вам о том, что открываемый файл уже открыт в другом процессе, чтоб открыть файл необходимо его закрыт.
Если это excel таблица, то скорее всего она уже открыта в Excel, по этому файл не открывается.
...
Рейтинг: 0 / 0
The process cannot access the file '' because it is being used by another process.
    #39890718
stek...
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Roman Mejtes,

Спасибо за информацию.

После записи файлов из БД в ОС, я их открываю,

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
 public bool FileGetSimple(int Identifier, string filePath)
        {
            var pa = Path.Combine(Path.GetTempPath(), Path.GetFileName(filePath));

            var statement = "SELECT Id, Data, FileName FROM StoredFile WHERE Id = @id;";
            var mc = MakeConnection(statement);
         

            mc.Parameters.AddWithValue("@id", Identifier);
            SqlDataReader reader = mc.ExecuteReader();

            if (reader.HasRows)
            {
                reader.Read();

                // the blob field
                int ndx = reader.GetOrdinal("Data");

                var blob = new Byte[(reader.GetBytes(ndx, 0, null, 0, int.MaxValue))];

                reader.GetBytes(ndx, 0, blob, 0, blob.Length);
                reader.Close();

                try
                {
                    //using (var fs = new FileStream(pa, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                    //{
                    //    fs.Write(blob, 0, blob.Length);
                    //}

                    if (File.Exists(pa))
                    {
                        File.Delete(pa);
                    }

                    using (var fs = new FileStream(pa, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                    {
                        fs.Write(blob, 0, blob.Length);

                    }


                    

                    //using (FileStream fs = File.Create(pa))
                    //{
                    //    fs.Write(blob, 0, blob.Length);
                    //}

                    //using (var stream = File.Create(pa))
                    //{
                    //File.WriteAllBytes(pa, blob);
                    //}
                }
                catch (IOException e) {
                    InformationWindow("Warning", e.Message + " Schlie&#223;en Sie diese Datei, um fortzusetzen.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    FileGetSimple(Identifier, filePath);
                }

   


                
            }



                   OpenFiles(pa); 

            return true;

        }

        private void OpenFiles(string tempFilePath)
        {
            

            using (sp = new Process())
            {
                  sp = Process.Start(tempFilePath); 
            }



            outputfiles = new List<string>();
            outputfiles.Add(tempFilePath);

        }





а затем закрываю.

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
                foreach (var item in outputfiles)
                {
                    if (!sp.HasExited)
                    {
                        //sp.WaitForExit();
                           sp.Kill(); 
                        

                        //if (Marshal.IsComObject(sp))
                        //{
                        //    Marshal.ReleaseComObject(sp);
                        //}

                        
                        //Marshal.ReleaseComObject(sp);
                    }
                    else
                              sp = null;
                    //sp.WaitForExit();
                    //sp.Close();

                    //Process[] ps2 = System.Diagnostics.Process.GetProcessesByName("EXCEL");
                    //foreach (Process p2 in ps2)
                    //{
                    //    Marshal.ReleaseComObject(p2);
                    //    p2.Kill();
                    //}

                    message.Attachments.Add(new Attachment(item));





Но к сожалению, я не могу найти в каком процессе открываемый файл уже открыт. Как видно из кода, пробывал по разному закрывать этот процесс. В слущае excel применял дополнительно Marshal.ReleaseComObject(sp). Не вышло. Где-то у меня этот файл использовается. Помогите, пожалуста разобраться..
...
Рейтинг: 0 / 0
The process cannot access the file '' because it is being used by another process.
    #39890963
stek...
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
При Debug mode моего приложения , код перепрыгивает с первого условия ниже на второе, а затем идет в исключение с сообщением "файл уже открыт". Хотя этот файл был убит Kill() методом и по факту закрыт. (Код того как файл был закрыт можно найти выше.)


Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
                try
                {

                    if (File.Exists(pa))
                    {
                        File.Delete(pa);
                    }

                    using (var fs = new FileStream(pa, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                    {
                        fs.Write(blob, 0, blob.Length);

                    }

                }
                catch (IOException e) {
                    InformationWindow("Warning", e.Message + " Schlie&#223;en Sie diese Datei, um fortzusetzen.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    Fil
...
Рейтинг: 0 / 0
The process cannot access the file '' because it is being used by another process.
    #39891027
Фотография Shocker.Pro
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Вероятно, какие-то дисковые операции выполняются ОС асинхронно. Попробуй вставить задержку (для того, чтобы понять, в этом дело или нет)
...
Рейтинг: 0 / 0
The process cannot access the file '' because it is being used by another process.
    #39891034
Roman Mejtes
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
уже обсуждали кстати похожую тему
https://www.sql.ru/forum/1317955/blokirovka-fayla?hl=attachment
автор темы писал, что файлы в Attachment находятся в открытом состоянии или как то так.
...
Рейтинг: 0 / 0
6 сообщений из 6, страница 1 из 1
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / The process cannot access the file '' because it is being used by another process.
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]